Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 322
Ofir Avatar asked Oct 19 '25 11:10

Ofir


1 Answers

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.

like image 185
AKX Avatar answered Oct 22 '25 00:10

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!