Apollo Client reactive variable state is not kept in cache after refreshing the page

1.3k views Asked by At

I have Apollo Client running on my React app, and trying to keep authentication info in a Reactive Variable using useReactiveVar. Everything works in the dummy function when I first set the variable, however it resets the state after refreshing the app.

Here's my cache.js:

import { InMemoryCache, makeVar } from "@apollo/client";

export const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        isLoggedIn: {
          read() {
            return isLoggedInVar();
          },
        },
      },
    },
  },
});

export const isLoggedInVar = makeVar();

export default cache;

Here's the component that reads the variable and renders different elements based on its state:

import React from "react";
import { useReactiveVar, useMutation } from "@apollo/client";
import MainButton from "../common/MainButton";
import { isLoggedInVar, userAddressVar } from "../../cache";
import { CREATE_OR_GET_USER } from "../../mutations/User";

const Profile = () => {
  const isLoggedIn = useReactiveVar(isLoggedInVar);

  const [createOrGetUser] = useMutation(CREATE_OR_GET_USER);

  const handleCreateOrGetUser = () => {
    const loginInput = {
      address: 'text',
    };
    createOrGetUser({
      variables: {
        loginInput: loginInput,
      },
    }).then((res) => {
      isLoggedInVar(true);
    });
  };

  const profileComponent = isLoggedIn ? (
    <div>Logged In</div>
  ) : (
    <div onClick={handleCreateOrGetUser} className="profile-image"></div>
  );

  return (
    <div className="profile-container">
      {profileComponent}
    </div>
  );
};

export default Profile;

This component gets re-rendered properly when I invoke handleCreateOrGetUser, however, when I refresh the page, it resets the isLoggedInVar variable.

What would be the proper way to use Reactive Variables here to persist the cache?

1

There are 1 answers

0
Maksim Huretski On

It's not currently achievable using Apollo API according to their documentation.

There is currently no built-in API for persisting reactive variables, but you can write variable values to localStorage (or another store) whenever they're modified, and initialize those variables with their stored value (if any) on app load.

There is a PR for that. https://github.com/apollographql/apollo-client/pull/7148