Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Query: How to useQuery when button is clicked

I am new to this react-query library.

I know that when I want to fetch data, with this library I can do something like this:

const fetchData = async()=>{...}  // it starts fetching data from backend with this line of code const {status, data, error} = useQuery(myKey, fetchData()); 

It works. But how to trigger the data fetching only when a button is clicked? , I know I probably could do something like <Button onPress={() => {useQuery(myKey, fetchData())}}/> , but how to manage the returned data and status...

like image 732
Leem.fin Avatar asked Jun 12 '20 08:06

Leem.fin


People also ask

How do I Refetch data in React query?

Using auto refetching in React Query To use the auto refetch mode, you can pass an optional parameter to the React Query hook called refetchInterval . The value is in milliseconds. const { isLoading, data } = useQuery( 'vehicle', async () => { const { data } = await axios.

How fetch data onClick in React JS?

To fetch data on button click in React: Set the onClick prop on a button element. Every time the button is clicked, make an HTTP request. Update the state variables and render the data.

What is query key in React query?

The Query Key is unique per query, so React Query can manage our cache for us, and if any part of the Query Key changes, the query will automatically fetch new data. In this example, if the user ID changes, the query will fetch new data for that specific user and store that data in the cache.


1 Answers

According to the API Reference, you need to change the enabled option to false to disable a query from automatically running. Then you refetch manually.

// emulates axios/fetch since useQuery expectes a Promise const emulateFetch = _ => {   return new Promise(resolve => {     resolve([{ data: "ok" }]);   }); };  const handleClick = () => {   // manually refetch   refetch(); };  const { data, refetch } = useQuery("key", emulateFetch, {   refetchOnWindowFocus: false,   enabled: false // turned off by default, manual refetch is needed });  return (   <div>     <button onClick={handleClick}>Click me</button>     {JSON.stringify(data)}   </div> ); 

Working sandbox here.
 

Bonus: you can pass anything that returns a boolean to enabled. That way you could create Dependant/Serial queries.

// Get the user const { data: user } = useQuery(['user', email], getUserByEmail)   // Then get the user's projects const { isIdle, data: projects } = useQuery(   ['projects', user.id],   getProjectsByUser,   {     // `user` would be `null` at first (falsy),     // so the query will not execute until the user exists     enabled: user,   } ) 
like image 100
Nicolas Hevia Avatar answered Sep 19 '22 19:09

Nicolas Hevia