React component not re-rendering after history.push()

  javascript, react-router, reactjs, use-effect

I have a homepage component that fetches reservations after it has rendered like this

const Index = ({ ...rest }) => {
  const [message, setMessage] = useState(null);
  const [items, setItems] = useState(null);

  useEffect(() => {
    fetch('reservation/getAll')
      .then(res => res.json())
      .then((res) => {
        setItems(res.result)
      });

  }, []);

when the user wants to edit a reservation he gets send to the edit reservation component like this

<Link to={`/reserveren/edit/${item.id}`} ><img class="action-icon" src={edit} /></Link>

after he has clicked the submit button he is being send back to the homepage component.

const handleReservation = (reservation) => {
    fetch(`/reservation/update/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        "date": reservation.date,
        "floor": reservation.floor,
        "moment": reservation.moment,
        "workplace": reservation.workplace
      }),
    })
    .then(history.push('/'))
  }

The problem is that the old data is still shown in the homepage component.
If I add items variable to the depencies array the data is updated but the homepage component keeps re-rendering no matter what.

So how can I only re-render the homepage component only if the items data actually changed and not keep re-rendering no matter what?

Source: React Router Questions

LEAVE A COMMENT