Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo Client Reactive variables - not trigger re render after updating the value

I'm trying to use the reactive variables:

My cache file :

import { makeVar } from "@apollo/client"

export const colorVar = makeVar('red')

File A (updating the value):

import { colorVar } from "cache"
colorVar('green')

File B (reading the value and should re-render after the value updated in File A):

import { colorVar } from "cache"
console.log(colorVar())

The update action in file A does not trigger the re-render of file B

like image 407
Ar26 Avatar asked Sep 01 '25 16:09

Ar26


2 Answers

cache file (use that cache for ApolloClient):

export const cache: InMemoryCache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        getColor()
          return colorVar();
        }
      }
    }
  }
});
export const colorVar = cache.makeVar('red')

Update the variable (File A):

import { colorVar } from "cache"
 colorVar('green')

Read the variable (File B):

 const GET_COLOR_Q = gql`
     query readColor {
        getColor @client
    }
  `;

  const { data } = useQuery(GET_COLOR_Q);

  console.log(data?.getColor)

Update: From Apollo Client 3.2.0 you can use the useReactiveVar hook to get the data (File B):

import { useReactiveVar } from '@apollo/client'
import { colorVar } from "cache"

// read
const color = useReactiveVar(colorVar)
console.log(color)

// write
colorVar('green')
like image 141
Ar26 Avatar answered Sep 04 '25 05:09

Ar26


You can do the following:

import { useReactiveVar } from "@apollo/client";
import { colorVar } from "cache"

// to read
const color = useReactiveVar(colorVar);

// to update
colorVar(your preferred color)
like image 35
briancoder Avatar answered Sep 04 '25 07:09

briancoder