1

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);
    });
  },
});

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes I can just use the defined hook but it will call the actual api /posts/1 and I dont want to make unnecessary call if i already have posts cached
in this case you can check if you have data cached under this key and enable the query based on that information. ` enabled: queryClient.getQueryData(["posts", id]).lenght > 0`
1

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.