简体   繁体   中英

How to update the UI after a delete mutation in react-apollo

I want the UI of my app to update after running a delete mutation in a react apollo component. The delete operation was successful but the UI did not update after the delete mutation. Below is a copy of my code, is there anything I am not getting right?

const deleteRoom = async (roomId, client = apolloClient) => {
  const user = await getUserDetails();
  const deleteResponse = await client.mutate({
    mutation: DELETE_ROOM,
    name: 'deleteRoom',
    variables: {
      roomId,
    },
    update: (cache, { data: roomDelete }) => {
      const data = cache.readQuery({
        query: GET_ROOMS_QUERY,
        variables: {
          location: user.location,
          office: '',
          page: 1,
          perPage: 8,
        },
      });
      data.allRooms.rooms = data.allRooms.rooms.filter(
        room => room.id !== roomDelete.deleteRoom.room.id,
      );
      console.log(data, '======');
      cache.writeQuery({
        query: GET_ROOMS_QUERY,
        data,
      });
    },
  });
  return deleteResponse;
};

I expected that the UI will be updated after executing the delete mutation, however, the UI doesn't get updated unless I do a force refresh.

N:B When I console log the data, it actually removed the deleted data after filtering it out of the array. The updated data is what I am writing back to the cache

This behaviour is described in docs:

The difference between cache.writeQuery and client.writeQuery is that the client version also performs a broadcast after writing to the cache. This broadcast ensures your data is refreshed in the view layer after the client.writeQuery operation. If you only use cache.writeQuery , the changes may not be immediately reflected in the view layer. This behavior is sometimes useful in scenarios where you want to perform multiple cache writes without immediately updating the view layer.

You can use refetchQueries option in mutate to force refresh.

Make sure the object going into update as the "data" includes returning values and is not an empty object and thus will not update UI.

update: (cache, { data: roomDelete }) // log data

So the mutations can work but no UI changes at once without update passing data forward.

And cache.writeQuery works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM