next.jsreact-querytanstackreact-query

How to refetch from a client component with useQuery


I have a client component that fetches the list of project and a dialog box that creates a project but I cant update the project list unless I have to do a manual refresh on the browser.

The flow is:

  1. navigating to project page should fetch the project list. (working)
  2. submitting the dialog form should create a project. (working)
  3. after submitting dialog should close. (working)
  4. after closing the dialog box, it should refetch or query the project page again. (not working)

solutions that Ive tried:

  1. calling revalidatePath('/projects') this wont work because the project page is client component.
  2. calling redirect('/projects') (I don't know why).
  3. tried calling window.location.reload(): inside the server component won't work to.

project page code:

"use client";

import React from "react";
import {DataTable} from "./dataTable";
import {columns} from "./columns";
import {getProjectLists} from "@/app/api/projectActions";
import {useQuery} from "@tanstack/react-query";
import {Button} from "@/components/ui/button";

const ProjectPage = () => {
  const {data, isError, isLoading, error, isSuccess} = useQuery({
    queryKey: ["projects"],
    queryFn: () => getProjectLists(1, 10),
  });

  console.log("data", data);

  if (isLoading) {
    return <div className="text-center">Loading...</div>;
  }

  return (
    <div className="w-4/5 mx-auto py-10">
      {data && <DataTable columns={columns} data={data} />}
      <Button>
        {/* (This should something like infinite scroll. check react-query for code) */}
        Load More
      </Button>
    </div>
  );
};

export default ProjectPage;

I'm still new to react-query so I don't have a clue. I tried using the refetch method won't work it will do a infinite call.

this wont work

if(isSuccess) {
 refetch();
}

I'm not sure if I'm missing something on react-query.


Solution

  • I'll assume this is what you are trying to achieve. After successfully making an entry into your database, you want to refetch the data without reloading the page.

    After you make a mutation in the dialog component, you can make use of the onSuccess callback function and invalidate projects to refetch the latest changes.

    More on invalidating queries after a mutation, visit the docs.

    import { useMutation, useQueryClient } from '@tanstack/react-query'
    
    const queryClient = useQueryClient()
    
    const mutation = useMutation({
      mutationFn: addProject,
      onSuccess: () => {
        queryClient.invalidateQueries({ queryKey: ['projects'] });
      },
    })