I'm using react query to fetch new movie info

63 Views Asked by At

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

There are 2 best solutions below

0
thelonglqd On BEST ANSWER

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 and react-query thinks it is the same request and use cached response instead of refetching the new one.

You should define queryKey line in this guide from tanstack

// An individual movie
useQuery({ queryKey: ['movieInfo', 5], ... })

The full document here: https://tanstack.com/query/latest/docs/framework/react/guides/query-keys#array-keys-with-variables

0
behnam kh On

I ran into a similar issue while using React Query. The problem seems to be that the queryKey used by React 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 the movieId in your queryKey.

This way, React Query knows to fetch new data for each movie.

Here's a quick fix:

const { movieId } = useParams();
const { data: movieInfo, isLoading } = useQuery({
  queryKey: ["movieInfo", movieId], // Updated queryKey
  queryFn: () => getMovieInfoById(movieId),
  onError: (err) => console.log(err),
});

Adding movieId to the queryKey makes each query unique to its movie, ensuring the correct movie data is fetched when you switch between movies.

Hope this helps!