I hope someone can explain the difference between updating through a useState and through cache.modify and why the one is preferred over the other, if that’s the case.
I have an input field where users can search for other users and they have the option to follow that user. I also have an option to unfollow that user:
method 1, useState
const [usersFollowed, setFollowedUsers] = useState<IUser[]>([]);
{error, loading, data: {returnFollowedUsers: followedUsers = {}} = {}},
useEffect(() => {
setFollowedUsers(followedUsers);
}, [followedUsers]);
const unfollowUser = async (user) => {
await unfollowUserMutation({
variables: {id: user.id},
}).then((res) => {
setFollowedUsers(res.data.unfollowUser);
});
};
I use the useEffect to populate the usersFollowed array when the component loads. And in the unfollowUser function I set the usersFollowed data with the response from the mutation.
But I can also do this by directly modifying the cache:
method 2, cache.modify
{error, loading, data: {returnFollowedUsers: followedUsers = {}} = {}},
const unfollowUser = async (user) => {
await unfollowUserMutation({
variables: {id: user.id},
update: (cache, {data}) => {
cache.modify({
fields: {
returnFollowedUsers: () => {
return [...data.unfollowUser];
},
},
});
},
});
};
Is there a significant difference between the usecases? I’ve noticed that useState only updates the component it’s called in, while cache.modify seems to trigger updates in other components that have a reference to that cache