Home > Software design >  React Query skip query when parameter is empty
React Query skip query when parameter is empty

Time:01-13

iam dealing with react query problem, i have separate file with all queries eg:

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 useQuerry to ommit fetching data when selectedPeriod param is empty (selected period is also being fetched from api when component mounts so i dont have any default value to set for selected period). is there any possibility to make useQuerry 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

CodePudding user response:

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
  })
}

CodePudding user response:

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 ✋

  • Related