Home > Enterprise >  how is it difference between queryFunction in react-query?
how is it difference between queryFunction in react-query?

Time:09-14

hi i'm beginner of react and react-query.
below code, it is correctly working!!

const { data, isLoading, isError, error } = useQuery("comments", () => {
    return fetchComments(post.id);
  });

and it is not working.

const { data, isLoading, isError, error } = useQuery("comments", fetchComments(post.id))

What is the difference between these?

CodePudding user response:

In first case, you are giving a function that will call fetchComments as a callback function. react-query will take that function and call it, which will call fetchComments

in second case, you are immidietaly running fetchComments function and passing returned value as param, and react-query is trying to run whatever fetchComments will return, which i assume is Promise and not a function

under some specific circumstances, you can just pass the function refernce without calling it, but you will be unable to pass any props:

const { data, isLoading, isError, error } = useQuery("comments", fetchAllComments)

Your first solution is the correct one.

and suggestion, you can use Arrow function without return, for me its more readable

const { data, isLoading, isError, error } = useQuery("comments", () => fetchComments(post.id));
  • Related