Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update component when fetching new page with useQuery?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

useQuery([getUsersQueryKey(), page], () => ...);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading