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

2.8k views Asked by At

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

3

There are 3 answers

0
Ar26 On BEST ANSWER

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')
0
briancoder On

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)
0
Maksim Brokhman On

As a small update to previous answers, you can do it in a more "traditional" react-hooks way like this:

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

const useColor = () => {
    const color = useReactiveVar(colorVar);
    const setColor = (color) => {
        colorVar(color);
    };

    return [color, setColor];
}