Search code examples
reactjsaxiosreact-big-calendar

react axios how to populate React Big Calendar


how I populate the big calendar with data from API Axios, create the array ....................................................................................

class Calendar extends Component {
  constructor() {
    super();

    this.state = {
      events: [],
      info: false,
      title: null,
      startDate: null,
      endDay: null,
      startTime: null,
      endTime: null,
      description: null
    };
    this.toggle = this.toggle.bind(this);
    this.toggleInfo = this.toggleInfo.bind(this);
  }
  handleChange = e => {

    this.setState({ [e.target.name]: e.target.value });

};

use the Axios to get a request from API......................

  loadCalendar() {
    axios
      .get(api + "api/calendar", {
        headers: {
          "Content-type": "application/json",
          Authorization: reqtoken
        }
      })

      .then(json => {
        json.data.data.data.map(data =>
          this.setState(
            events({
              title: data.title,
              start: data.startDate,
              end: data.endDate
            })
          )
        );

      })
      .catch(erros => {
        console.log(erros);
      });
  }

  componentDidMount() {
    this.loadCalendar();
  }

reder retorn html with data api............................................................

render() {
    return (
 <CardBody style={{ height: "40rem" }}>
            <BigCalendar
              className="d-sm-down-none"
              style={{ height: "-webkit-fill-available" }}
              {...this.props}
              events={events}
              views={["month", "week", "day"]}
              step={30}
              defaultDate={new Date(currYear, currMonth, 1)}
              defaultView="month"
              toolbar={true}
              localizer={localizer}
            />
            <BigCalendar
              className="d-md-none"
              {...this.props}
              events={events}
              views={["day"]}
              step={30}
              defaultDate={new Date(currYear, currMonth, 1)}
              defaultView="day"
              toolbar={true}
              localizer={localizer}
            />
          </CardBody>
)

Solution

  • When you are setting the events, you are overwriting the previous events. You are also using setState improperly, you should pass an object to that function.

    Instead you could do something like the following for axios success callback:

    .then(json => {
      const events = json.data.data.data.map(data =>
        return {
          title: data.title,
          start: data.startDate,
          end: data.endDate
        }
      );
      this.setState({ events });
    })
    

    This assumes that your events data is actually returned in that nested object json.data.data.data (which seems odd, but it is what it is).