Next.js Discord

Discord Forum

After page reload, my query does not run unless I have a context switch / refocus on the window.

Unanswered
Cuban Crocodile posted this in #help-forum
Open in Discord
Cuban CrocodileOP
Everything works as expected locally, but when deployed, i think useEffect runs before the cache can be restored?
use client";

import { Build, Recipe } from "@/__generated__/graphql";
import { useEffect, useMemo } from "react";
import { useQuery, useReactiveVar } from "@apollo/client";

import { USER_BUILDS } from "@/app/graphql/queries/recipe";
import { useSession } from "next-auth/react";
import { userRecipeList } from "@/app/graphql/reactiveVar/recipes";

export default function RecipeLoader() {
  const { status: sessionStatus } = useSession();
  const { data, loading, error } = useQuery(USER_BUILDS, {
    skip: sessionStatus !== "authenticated",
    fetchPolicy: "cache-and-network"
  });
  const recipeList = useReactiveVar(userRecipeList);

  useEffect(() => {
    if (data) {
      const recipes = convertRecipes(data);
      recipes.sort((a, b) => a.name.localeCompare(b.name));
      userRecipeList(recipes);
    }
  }, [data]);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>{error.message}</div>;
  }

  return <div>{`${recipeList.length} Recipes Loaded`}</div>;
}

I'm using localForage and apollo-cache-persist for cache persist. Anyone have any advice?

3 Replies

Cape lion
I don't know the libs you are using but can you try to put a setTimeout inside your useEffect() to see if this really is the delay that cause this behavior.
Cuban CrocodileOP
That's seems like a smart choice for debugging. I'll give it a go. thanks!
Cuban CrocodileOP
The answer was the skip: sessionStatus !== "authenticated". I was needed elsewhere for a session related call, so I included it automatically. I feel pretty silly. I'm just glad my code works now.