Reputation: 145
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
Upvotes: 1
Views: 2780
Reputation: 1600
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.
Upvotes: 1
Reputation: 8418
This behaviour is described in docs:
The difference between
cache.writeQuery
andclient.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 theclient.writeQuery
operation. If you only usecache.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.
Upvotes: 1