React Query w/NextJS - I'm noticing that, once my page has loaded, the query does not execute until I have clicked within the browser's viewport

Viewed 168

I'm new to React Query and am wondering what that's about--forestalling execution of my GraphQL query until I click anywhere within the browser's viewport. Shouldn't the query just execute straight away?

Here's my code:

import { useUrlHashParameters } from "../src/hooks";
import { useQuery } from "react-query";
import { gql, request } from "graphql-request";

export default function Home() {
  const parameters = useUrlHashParameters();
  const { data } = useQuery("test", async () => {
    if (parameters) {
      localStorage.setItem("accessToken", parameters.accessToken);
      const url = "http://localhost:3001/graphql";
      const document = gql`
        query {
          products {
            id
            title
            description
            totalInventory
            __typename
          }
        }
      `;
      const requestHeaders = {
        Authorization: `Bearer ${localStorage.getItem("accessToken")}`,
      };

      return await request({
        url,
        document,
        requestHeaders,
      });
    }
  });

  console.log(data);

  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <Image
          src="/blah-logo.png"
          alt="Blah"
          width={300}
          height={75}
        />

        {data?.products.map(({ title }, index: number) => (
          <div key={index}>{title}</div>
        ))}
      </main>
    </div>
  );
}
1 Answers

Shouldn't the query just execute straight away?

Yes, it should, and it likely does. My best guess is that on the first render, the parameters are undefined, and since you check for if (parameters) in the queryFn without doing anything in an else branch, the queryFn will just return a Promise that resolves to undefined (which will be illegal in v4 btw).

Then, when you focus the window, you get a refetch, in which case parameters likely exist.

You can verify this by putting a log statement into the queryFn, but outside the if statement.

Further, all parameters that your query uses should be part of the query key. That makes sure that you get automatic refetches when the parameters are changing. So changing your query key to:

["test", parameters]

and setting: enabled: !!parameters instead of the if to stop the query from running if there are no parameters is likely the best course of action:

const parameters = useUrlHashParameters();
const { data } = useQuery(
  ["test", parameters],
  () => request({...}),
  {
    enabled: !!parameters
  }
)
Related