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
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')
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With