I am dealing with react query problem, I have separate file with all the queries:
const useFetchApTableQuery = (date: string): UseQueryResult => {
const axiosClient = axios.create()
const fetchApTableQuery = async (): Promise<AxiosResponse> => {
const res = await axiosClient.get(`${API_ROUTES.apTable}?date=${date}`)
return res.data.data.map((record: any) => APParser(record))
}
return useQuery([date], fetchApTableQuery, {
})
}
and then iam calling my query in component like this
const APTablePage = (): JSX.Element => {
const [selectedPeriod, setSelectedPeriod] = useState<string>('')
const { data: tableData } = useFetchApTableQuery(selectedPeriod)
....
}
The problem is need useQuery to omit fetching data when selectedPeriod param is empty (selected period is also being fetched from api when component mounts so I don't have any default value to set for selected period). is there any possibility to make useQuery pass for example null to {data:tabledata} variable when selectedPeriod is empty string ?
Thank you :-)
I have tried dealing with this via useEffect but unfortunately I cannot call hooks in useffect
You can set the enabled property to be true when date is not empty
const useFetchApTableQuery = (date: string): UseQueryResult => {
const axiosClient = axios.create()
const fetchApTableQuery = async (): Promise<AxiosResponse> => {
const res = await axiosClient.get(`${API_ROUTES.apTable}?date=${date}`)
return res.data.data.map((record: any) => APParser(record))
}
return useQuery([date], fetchApTableQuery, {
enabled: date.length > 0
})
}
i'm not sure about my answer but we can disable a query from automatically running, you can use the
{ enabled: false } the optional object argument that you pass to customize all behaviors of react-query read more at the end ,
useQuery([date], fetchApTableQuery, { enabled : false}) // this will always disabled .
useQuery([date], fetchApTableQuery, { enabled : pram.length > 0}) // with condition enabled or disabled
the enable key is in scope whenever the function Component run you can pass to it any value outside the scope that control your fetching requests
i really encourage you to read the docs it's very simple to master ReacQuery ,have fun ✋😊 !
https://react-query-v3.tanstack.com/guides/disabling-queries
https://react-query-v3.tanstack.com/guides/dependent-queries
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With