Home > OS >  How to update component when fetching new page with useQuery?
How to update component when fetching new page with useQuery?

Time:11-02

Im trying to fetch and display data from my own API using axios and useQuery from react-query. Since Im using pagination in my API, I also implmented table with option to choose page that displays data of the current page. Evrything works fine until I tried to go to next the page. When I do that, the table component that holds the data is not updated. When I print the response into console, all the data are updated but not the table component. The table component updates when I for example go to another tab in my browser and then back.

Im using axios like this in separated file:

export const getUsersQueryKey = () => "users";

export const useUsersQuery = (page: number) =>
  useQuery(getUsersQueryKey(), () =>
    axios
      .get(`http://localhost:8081/api/users?pageNumber=${page}&pageSize=2`)
      .then((response) => response.data.content as User[])
  );

This is my container where Im rendering the data:

const UsersContainer: React.FunctionComponent = () => {
  const [page, setPage] = useState(0);

  const { data, isLoading } = useUsersQuery(page);

  if (isLoading) return <LinearProgress />;

  const ChangePage = (event: any, page: number) => {
    setPage(page - 1);
  };
  
  const users = data?.map((user) => <UserItem key={user.id} user={user} />);

 return (
   <Table>{users}</Table>
);};

How can I update table component with the new data or is my code missing something?

CodePudding user response:

Your query does not listen to page changes. You should include it in the query key.

useQuery([getUsersQueryKey(), page], () => ...);
  • Related