Search code examples
react-nativeredux-toolkit

How do I manage a query where parameters need to change?


How do I update queryParameters such that when I call refetch, the new parameters are used?

Now it seems like it always uses the parameters sent into useGetDataQuery, even if I change queryParameters.

const queryParameters = { id: id, startDate: '2024-05-16', stopDate: '2024-06-15' }
const { refetch, isLoading, isFetching } = useGetDataQuery(queryParameters)

I.e. I want to update startDate and stopDate and refetch with the updated values.

I've tried finding my answer here, but as far as I can tell there's no solution with updated parameters to refetc. React-Query: How to useQuery when button is clicked


Solution

  • I will summary your case:

    • You need change something in queryParameters
    • After queryParameters change, you need re-call some api.

    My idea is using setQueryParameters to change queryParameters by useState and use useQuery to call api when queryParameters has been changed, queryParameters is tracked by useQuery via queryKey.

    const [queryParameters, setQueryParameters] = useState({
      id: id,
      startDate: '2024-05-16',
      stopDate: '2024-06-15',
    });
    
    const getData = (queryParameters) => {
      // call api
    };
    
    const {data, isFetching, isLoading} = useQuery({
      queryKey: [queryParameters],
      queryFn: () => getData(queryParameters),
    });
    

    I hope my code can resolve your problem.