skip to Main Content

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


  1. import { useQuery } from 'react-query';
    import { useContext } from 'react';
    import { MyContext } from './path/to/your/context'; // Import your context
    
    // Assuming FETCH_ORDERS_API and pageNumber are defined somewhere above
    
    const YourComponent = () => {
        const { pageNumber } = useContext(MyContext); // Assuming pageNumber is part of your context
    
        const { isPending, isError, data, refetch } = useQuery({
            queryKey: ['ordersFetch', pageNumber.order], // Include pageNumber.order in queryKey
            queryFn: () => fetch(FETCH_ORDERS_API + pageNumber.order).then((res) => res.json())
        });
    
        // Call refetch whenever pageNumber.order changes
        React.useEffect(() => {
            refetch();
        }, [pageNumber.order]);
    
        return (
            // Your component JSX here
        );
    };
    
    export default YourComponent;
    
    Login or Signup to reply.
  2. 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
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search