8

I am using react-query to call an API. The call works well and is performed each time a query value is updated in an input field.
Unfortunately, it also triggers an API call even when the query is empty.

For example, when the user loads the app, the input (and hence query) will be blank.

How to trigger API calls only when there is a query?

Code

// API call
export async function myQuery(query) {
  try {
    const res = await ax.get("myapiurl", {
      params: { query },
    });
    return res.data;
  } catch {
    return null;
  }
}

// react-query
const { status, data } = useQuery(
  ["myquery", { query }],
  () => myQuery(query)
);

4 Answers 4

15

There is an enabled flag in react-query for this exact use case.

Usage example

const { status, data } = useQuery(
  ["myquery", { query }],
  () => myQuery(query).
  { enabled: !!query }
);

Docs for reference

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

2 Comments

Is there a way to prevent fetching when refetch method get called? react-query?
Here is a slightly more relevant doc link: tanstack.com/query/v4/docs/guides/dependent-queries
1

You can achieve that with a simple if sentence:

// apicall
export async function myQuery(query) {
  try {
    const res = await ax.get("myapiurl", {
      params: { query },
    });
    return res.data;
  } catch {
    return null;
  }
}

// react-query
  const { status, data } = useQuery(
    ["myquery", { query }],
    () => {
      if (query) {
        return myQuery(query)
      }
  );

2 Comments

It doesn't work, I still have the loader.Also, I tried to write if(!query){null} before the try/catch block, but when doing so, react-query keeps loading forever.
I editted the code, please try this now. You might want to delete the lone return in the useQuery callback
0

I encountered the same error while working on a project that involves making API requests based on user input. After conducting my research, I discovered a solution that you can refer to for more clarity. You can check out TanStack Query for further details. [dependent queries ][1].

To modify the useQuery hook to only fetch data when a user enters and submits a value, you need to make the following adjustments:

const { data, isError, isInitialLoading } = useQuery({
    queryKey: ['images'],
    queryFn: async () => {
        const { data } = await customFetch.get(`/photos?page=1&query=${userInput}&client_id=${import.meta.env.VITE_CODE_BOOK}`);

        const { results } = data;

        return results;
    },
    // setUserInput to an empty string and enable page render
    onSuccess: () => {
        setUserInput('');
        toast.success('Success');
   },
  // force usequery to only fetch when user submits a value
    enabled: !!userInput,
});

You can the use isInitialLoading to display your loader and isError in the case of error [1]: https://tanstack.com/query/latest/docs/react/guides/dependent-queries

Comments

0

if you use enabled then uoy can`t revalidate query by key. I advice use useQueries and return empty array if query is null

// Then get the users messages
const useMyQuery = (query: string | null) => {
  return useQueries({
    queries: query
    ? [query].map(q => {
        return {
          queryKey: ['myapiurl', q],
          queryFn: () => myQuery(q),
        };
      })
  : [], // if query is null, an empty array will be returned
})

}

it is pain...

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.