Reputation: 525
For example, I've this query to fetch a list:
const list = useQuery('list', fetcher);
But I need something like a prechecking function before react-query execute that, I mean something like this:
const appQueryClient = new QueryClient({
defaultOptions: {
queries: {
checkSomethingBeforeExecute: () => {
if (itShouldExecute) {
return true; // start fetching
} else {
return false; // don't fetch and abort query
}
}
},
},
});
In fact, that checkSomethingBeforeExecute
is my idea... but I'm looking for any option or trick to implement something like that.
If you remember, there is a select
option to transform data after fetching, but I need something to determine query exec before anything start with fetcher function.
##new update##
I updated my question for this example:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider, useQuery } from 'react-query';
const client = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: false
}
}
});
const fetcher = () => fetch('https://randomuser.me/api/?results=5').then(res => res.json());
function App() {
const [id, setId] = useState(null);
const { data } = useQuery(['list', id], fetcher, { enabled: !!id });
const change = (e) => {
setId(e.target.value);
}
return (
<div>
<select onChange={change}>
{
Array(30).fill().map((i, ii) => <option value={ii} key={ii}>item - {ii}</option>)
}
</select>
</div>
)
}
const rootElement = document.getElementById('root');
ReactDOM.render(<QueryClientProvider client={client}><App /></QueryClientProvider>, rootElement);
There is a select input to handle changing state for each id
and react-query doesn't retrieve cache and fetches again for even same IDs...
Thanks
Upvotes: 1
Views: 7049
Reputation: 29046
if your query is not ready to be executed, the enabled
option is what you are looking for:
https://react-query.tanstack.com/guides/dependent-queries
if you want to "not fetch" and "abort" the query (not sure what aborting means here), you can return a rejected Promise from your queryFn:
useQuery(key, () => {
if (itShouldExecute) {
return axios.get(...)
}
return Promise.reject(new Error("something error"))
})
be aware that this will put the query in an error state and potentially trigger retries. The enabled option will not run the queryFn at all and will put your query into idle
state. I think these are the two available options.
Upvotes: 2