Question

React query - force querying new data for a new object id

I'm using react query to fetch data on a blog post, according to its Id. When I visit a certain blogpost and then navigate to another one, it first presents me the data from the previous blogPost, and then re-render the page with the new information. It seems that the data is first of all fetched from the cache, and after that get refreshed.

Code:

const BlogPost = () => {
// Getting the blogPostId from the Url
  const { blogPostId } = useParams();

// Querying the blogPostData from the server using its id. (here is the problem probably...)
  const { data: blogPostData } = useQuery<BlogPostType>({
    queryKey: ["getBlogPost"],
    queryFn: () => apiClient.getPostById(blogPostId),
  });

  return (
    <div>
      <h1>{blogPostData?.title}</h1>
      <hr/>
      <p>{blogPostData?.description}</p>
    </div>
  );
};

Any solution? (I want that the new data will appear immediately)

 4  39  4
1 Jan 1970

Solution

 2

The blog post ID must be part of the key.

const { data: blogPostData } = useQuery<BlogPostType>({
  queryKey: ["getBlogPost", blogPostId],
  queryFn: () => apiClient.getPostById(blogPostId),
});

As documented:

When a query needs more information to uniquely describe its data, you can use an array with a string and any number of serializable objects to describe it. [...] It's common to pass an ID, index, or other primitive to uniquely identify the item: useQuery({ queryKey: ['todo', 5], ... })

The same pattern applies to swr, and in fact is somewhat of an analogue to the deps you'd give useEffect.

2024-07-24
AKX