Nam Nguyen
Nam Nguyen

Reputation: 13

Full calendar - Can not refresh events in react

I use Full Calendar in my React project. I can not refresh the calendar although I make an update on the state.

Here is my sample code: https://codesandbox.io/embed/fullcalendar-react-jp7n1

In this sample, I change the title of events when user clicks on the Change title button, but nothing changes. I there anything that I miss?

Thanks for your help.

import React from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction"; 
import "./styles.css";
import "@fullcalendar/core/main.css";
import "@fullcalendar/daygrid/main.css";
import "@fullcalendar/timegrid/main.css";

export default class DemoApp extends React.Component {
  calendarComponentRef = React.createRef();

  state = {
    calendarWeekends: true,
    calendarEvents: [
      // initial event data
      { title: "Event 1", start: new Date() },
      { title: "Event 2", start: new Date() },
      { title: "Event 3", start: new Date() }
    ]
  };

  render() {
    return (
      <div className="demo-app">
        <div className="demo-app-top">
          <button onClick={this.changeTitle}>Change title</button>
        </div>
        <div className="demo-app-calendar">
          <FullCalendar
            defaultView="dayGridMonth"
            header={{
              left: "prev,next today",
              center: "title",
              right: "dayGridMonth,timeGridWeek,timeGridDay,listWeek"
            }}
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            ref={this.calendarComponentRef}
            weekends={this.state.calendarWeekends}
            events={this.state.calendarEvents}
          />
        </div>
      </div>
    );
  }

  changeTitle = () => {   
    let events = [...this.state.calendarEvents];
    events[0].title = new Date().toTimeString();
    events[1].title = new Date().toTimeString();

    this.setState({ calendarEvents: events });
  };
}

Upvotes: 0

Views: 4736

Answers (1)

SunnyDark
SunnyDark

Reputation: 321

Full calendar uses deep equality check to test for changes and since the object of the event inside the array is not changed (it's the same object by reference) it doesn't detect the change. You need to create a new event object to update it.

let events = [ ...this.state.calendarEvents];

    events[0] = {
      title: new Date().toTimeString(),
      start: events[0] .start
    }
    events[1] = {
      title: new Date().toTimeString(),
      start: events[1].start
    }

    this.setState({ calendarEvents: events});

Upvotes: 3

Related Questions