0

I am trying to get isLoading returned from a custom React Query hook.

Here is my hook:

async function getUserDiscussions(
  user: User | null
): Promise<Post[] | null> {
  const { data } = await axiosInstance.get(
    `/getUserPosts`,
  );
  return data;
}

export function usePosts(): Post[] {

  const fallback: Post[] = [];
  const { data: posts = fallback } = useQuery(
    [
      queryKeys.posts,
    ],
    () => getUserDiscussions(user),
  );
  return posts;
}

I am then calling the hook in a component like this:

const posts = usePosts()

I would like to then be able to access isLoading and update the UI accordingly.

How can I access isLoading from the query in the custom hook and use it in the component?

3
  • Just return the query itself and you can access it's methods! Commented Jan 21, 2023 at 12:51
  • Thanks @VahidAlimohamadi, can you give me an example of how I can do that please? Commented Jan 21, 2023 at 12:53
  • The first answer is showing how @sgrmhdk returning the isLoading method. Also you can return the whole query obj. return useQuery(...) instead of posts and isLoading. Commented Jan 21, 2023 at 12:57

1 Answer 1

1

You can get it from useQuery and return the same from your function.

export function usePosts(): Post[] {

  const fallback: Post[] = [];
  const { data: posts = fallback, isLoading } = useQuery(
    [
      queryKeys.posts,
    ],
    () => getUserDiscussions(user),
  );
  return {posts,isLoading};
}
Sign up to request clarification or add additional context in comments.

3 Comments

tanstack.com/query/latest/docs/react/reference/… You can refer documentation here.
it seems there must be a type error because of you determined the function return type as an array.
Hi @VahidAlimohamadi, Yes it won't let me return posts as it isn't defined on the types.

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.