I was building a movies web app using react and tmdb api. I have a page called Movies.jsx
where all movies are fetched using react query and that works fine. I also have movieInfo.jsx
page that responsible for showing details of a specific movie based on id in url using also react query.
The problem here is when I open a movie and go back to the movies list and then open another one, the movieInfo
page shows the previous movie data. After some seconds it’s re rendering the UI and shows the one I clicked on.
How do I solve this issue so the previous movie info will not show after clicking a different movie?
I’m new to react query, Thanks
Trying to fetch data using react query
Code of movieInfo.jsx :
const { movieId } = useParams();
const { data: movieInfo, isLoading } = useQuery({
queryKey: ["movieInfo"],
queryFn: () => getMovieInfoById(movieId),
onError: (err) => console.log(err),
});
2
Answers
I think the reason for your issue is default caching mechanism of
react-query
.You defined a query key for movie info api call
movieInfo
andreact-query
thinks it is the same request and caching the response instead of refetch the data.You should define queryKey line in this guide from tanstack
The full document here: https://tanstack.com/query/latest/docs/framework/react/guides/query-keys#array-keys-with-variables
I ran into a similar issue while using React Query. The problem seems to be that the
queryKey
used byReact Query
isn’t being updated for each movie, which causes it to initially load data from the cache (hence showing the previous movie’s info). To fix this, make sure to include themovieId
in yourqueryKey
.This way,
React Query
knows to fetch new data for each movie.Here’s a quick fix:
Adding
movieId
to thequeryKey
makes each query unique to its movie, ensuring the correct movie data is fetched when you switch between movies.Hope this helps!