I have an odd situation that seems to be working, but might not be per design according to the documentation.
I have a mutation:
// AddMovieToDashboard.tsx
const [addUserToMovie] = useMutation(resolvers.mutations.AddUserToMovie);
const addMovie = async (movie: IMovie) => {
await addUserToMovie({
variables: {...movie, tmdb_id: movie.id},
update: (cache) => {
cache.modify({
fields: {
moviesFromUser: () => {},
},
});
}},
);
};
This mutation adds a movie to a database table and creates a many to many relation between a user and the movie. I’ve added the update
function because before I was using reactive variables to store the new movie array in a reactive variable and in a different component I would react if that variable would’ve changed to render a new view. But I’ve read that it’s better to do this directly on the cache. It saves a lot of code at least.
In my MovieOverview
component I render a list of movies added by the user:
// MovieOverview
const MovieOverview = () => {
const {error, loading, data: {moviesFromUser: movies} = {}} =
useQuery(resolvers.queries.ReturnMoviesFromUser, {
variables: {userId: currentUserVar().id},
});
if (error) return (<div>error</div>);
if (loading) return (<div>loading...</div>);
return (
<div>
{movies.length}
</div>
);
};
So now when I add a movie the MovieOverview
component rerenders and it does a request to the server for a list of movies which then returns the updated list increasing the movies.length
by 1.
So while this is all working I have a feeling there’s something going wrong because I believe I don’t need the query in the MovieOverview
component to grab the new array from the server.