Home > Net >  Passing multiple parameters to query function (useQuery) from React-Query
Passing multiple parameters to query function (useQuery) from React-Query

Time:01-15

I want to execute the getUsers function using useQuery from react-query. The useQuery function has 3 parameters but I don't know what is the syntax to pass them, the code below doesn't work, nothing appears on the page

  const { isLoading, isError, data } = useQuery(
    ["getUsers"],
    getUsers(
      location?.state?.code || cookies.get("code"),
      cookies.get("accessToken"),
      cookies.get("expirationDate")
    )
  );

The getUsers function is below :

import axios from "axios";

export default async function getUsers(code, accessToken, expirationDate) {
  return axios.post(`${import.meta.env.VITE_NAME_API_URL}/get-users`, {
    code,
    accessToken,
    expirationDate,
  });
}

CodePudding user response:

If you want to pass parameters to some function that is used by useQuery you need to specify them in the dependency array.

React Query Dependent Queries Documentation: https://tanstack.com/query/latest/docs/react/guides/dependent-queries?from=reactQueryV3&original=https://react-query-v3.tanstack.com/guides/dependent-queries

Documentations example:

const { data: user } = useQuery({
  queryKey: ['user', email],
  queryFn: getUserByEmail,
})

Your exmaple:

    const code = location?.state?.code || cookies.get("code")
    const accessToken = cookies.get("accessToken")
    const expDate = cookies.get("expirationDate")

     const { isLoading, isError, data } = useQuery(
    ["getUsers", code, accessToken, expDate],
    getUsers(
      code,
      accessToken,
      expDate
    )
  );
    

CodePudding user response:

The useQuery hook expects you to provide (at least) 2 things. A query key (the parameters that should be used to cache/fetch the data), and an async function which will receive the query key and should return the result of the query.

In your example you have an async function which takes a bunch of parameters, but not a query key. So you'll want to wrap that function in a query function that you can pass to useQuery.

e.g.

  const code = location?.state?.code || cookies.get("code")
  const accessToken = cookies.get("accessToken")
  const expDate = cookies.get("expirationDate")

  const { isLoading, isError, data } = useQuery(
    ["getUsers", code, accessToken, expirationDate],
    ({queryKey: [queryType, ...params]}) => getUsers(...params)
  );
  • Related