TanStackT
TanStack12mo ago
3 replies
moderate-tomato

Query is fetching multiple times

I made a simple application to test this.
1. I created a server action with a delay to fetch the current data
2. I have a page "my-data" where I display the data
3. Then I go to "edit-data" where I simply invoke the removeQueries and then go back to "my-data"
4. On "my-data" the query is called 2 times

Why is this happening?

Code:

/actions.ts

"use server";
import { delay } from "../delay";
export async function getMyData() {
  await delay(3000);
  return {
    time: Date.now().toString(),
  };
}


/my-data/page.tsx

import Link from "next/link";
import MyData from "./my-data";

export default function Page() {
  return (
    <div>
      <div>My Data:</div>
      <MyData></MyData>
      <Link href={"/edit-data"}>Go to Edit Data</Link>
    </div>
  );
}


/my-data/my-data.tsx

"use client";

import { useQuery } from "react-query";
import { getMyData } from "./actions";

export default function MyData() {
  const { data, isLoading } = useQuery({
    refetchOnWindowFocus: false,
    queryKey: ["my-data"],
    queryFn: getMyData,
  });
  return (
    <div>
      <div>
        {isLoading ? <div>Loading...</div> : <div>Data: {data?.time}</div>}
      </div>
    </div>
  );
}


/edit-data/page.tsx

"use client";

import { useRouter } from "next/navigation";
import { useQueryClient } from "react-query";

export default function Page() {
  const router = useRouter();
  const client = useQueryClient();
  return (
    <div>
      <div>Edit Data</div>
      <button
        onClick={async () => {
          // clear the cache
          client.removeQueries({ queryKey: "my-data", exact: false });

          // Go back to my data
          router.push("/my-data");
        }}
      >
        Save
      </button>
    </div>
  );
}
Was this page helpful?