TanStackT
TanStack5w ago
10 replies
ill-bronze

useQuery in dedicated module -> No page refresh

Hey,
I have been struggling to understand why my page is not being refreshed with my fetched data when I put useQuery into an own dedicated file.
This works:

// CustomerPage.tsx
import { useQuery } from '@tanstack/react-query';

const CustomerPage = () => {

    const { data:customer, isFetching } = useQuery({
    queryKey: ['customer', '123'],
    queryFn: async () => {
      const response = await fetch( `/api/customer/123` );
      return response.json();
      // Your API call here
    },
  });

  return (
    <div>
        <h1>Customer Page</h1>
        { isFetching && <p>Loading customer data...</p> }
        { customer && customer.data && (
          <div>
            <h2>Customer Details</h2>
            <p><strong>Name:</strong> { customer.data.name1 } { customer.data.name2 }</p>
          </div>
        ) }

    </div>
  );
}

export default CustomerPage;

But this approach does not:
//customerQuery.ts
import { useQuery } from "@tanstack/react-query";

const customerQuery = ( customerId: string ) => {

    return useQuery({
    queryKey: ['customer', '123'],
    queryFn: async () => {
      const response = await fetch( `/api/customer/${ customerId }` );
      return response.json();
    },
  });
};

export default customerQuery;

//CustomerPage.tsx
import customerQuery from '../../queries/customerQuery';

const CustomerPage = () => {

  const { data:customer, isFetching } = customerQuery('123');

  return (
    <div>
        <h1>Customer Page</h1>
        { /* Part below is never being rendered */ }
        { isFetching && <p>Loading customer data...</p> }
        { customer && customer.data && (
          <div>
            <h2>Customer Details</h2>
            <p><strong>Name:</strong> { customer.data.name1 } { customer.data.name2 }</p>
          </div>
        ) }

    </div>
  );
}
export default CustomerPage;

Can somebody please explain why this happening?

Thanks in advance
Was this page helpful?