0

This is my simle React Query function for useQuery

 var { isPending, isError, data } = useQuery({
        queryKey: ['ordersFetch'],
        queryFn: () => fetch(FETCH_ORDERS_API + pageNumber.order).then((res) => res.json())
    })

I am changing the pageNumber.order by using the contextApi which results in URL change, but it is not refetching the data, how can i fetch data whenever my url changes here ?

On one screen I change the pageNumber state and then navigate to the different screen at that moment useQuery refetches the data but not when i change the state and remains on the same screen

2 Answers 2

0

Try to use use location hooks from react-router-dom to refetch the data when URL is changed.


import { useQuery } from 'react-query';
import { useLocation } from 'react-router-dom';

const MyComponent = () => {
  const location = useLocation();

  const { isPending, isError, data, refetch } = useQuery({
    queryKey: ['ordersFetch', location.pathname], // Include pathname in queryKey
    queryFn: () => fetch(FETCH_ORDERS_API + location.pathname).then(res => res.json())
  });

  // Listen for changes in the location (URL) and refetch data when it changes
  useEffect(() => {
    refetch();
  }, [location.pathname]); // Trigger refetch when pathname changes

  return (
    // Your component JSX
  );
};
Sign up to request clarification or add additional context in comments.

Comments

0

React Query cache data by the queryKey you provided. You need to update the queryKey to make sure it is unique each time you want to fetch a new data.

 var { isPending, isError, data } = useQuery({
        queryKey: ['ordersFetch', pageNumber.order],
        queryFn: () => fetch(FETCH_ORDERS_API + pageNumber.order).then((res) => res.json())
    })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.