tryingToBeBetter
tryingToBeBetter

Reputation: 425

React Query how to use cache data to fetch by id?

I am fetching all posts from json place holder api /posts and cache it as query cache key as ["posts"]

I want to use the cache posts to fetch by id

Right now I am trying

export const useGetPostById = (id: any) => {


const service = getQueryService();
  const queryClient = useQueryClient();
  const { data: post } = useQuery(["post", id], () => {
    return service.getPostById(id);
  });
  return {
    post,
  };
};

and on my component trying to fetch this data by

const stupidData = queryClient.getQueryData(["posts", id]);
console.log(stupidData, "STUPID");

however here stupidData is undefined..

Here is how I'm fetching all posts

const { data: posts } = useQuery(["posts"], service.getPosts, {
  enabled: true,
  cacheTime: Infinity,
  onSuccess: (data) => {
    console.log("DATA", data);
    data?.data.map((post: any) => {
      queryClient.setQueryData(["posts", post.id], post);
    });
  },
});

Upvotes: 1

Views: 8746

Answers (2)

tryingToBeBetter
tryingToBeBetter

Reputation: 425

Instead of just accessing the cache, I was just able to query the posts and find by id like

  const myItem = posts?.data.find((item: any) => {
return item.id === Number(id);
});

Upvotes: 1

Oliver Ilmjärv
Oliver Ilmjärv

Reputation: 341

instead of accessing the queryData from queryClient.getQueryData() can you use the defined hook in the component ?

At first, if the query hasnt been made yet, the data is supposed to be undefined. but since there is no state change, the component will not rerender to get the fetched query data.

export const useGetPostById = (id: number) => {
  const service = getQueryService();
  const queryClient = useQueryClient();
  const { data: post } = useQuery(["posts", id], () => service.getPostById(id);
  );
  return {
    post,
  };
}

const Component = () => {
  const id = 10;
  const { post } =  useGetPostById(id)
  ...
}

Addressing your last code example, you can delete the onSuccess function content. this is handeled automatically. The queryClient will save the incoming data to the same key you are already requesting it with. In this case, its ["posts", id: number]

Edit: added extra information

Upvotes: 2

Related Questions