缓存文件(为 ApolloClient 使用该缓存):
export const cache: InMemoryCache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
getColor()
return colorVar();
}
}
}
}
});
export const colorVar = cache.makeVar('red')
更新变量(文件 A):
import { colorVar } from "cache"
colorVar('green')
读取变量(文件 B):
const GET_COLOR_Q = gql`
query readColor {
getColor @client
}
`;
const { data } = useQuery(GET_COLOR_Q);
console.log(data?.getColor)
更新:从 Apollo Client 3.2.0,您可以使用 useReactiveVar 挂钩来获取数据(文件 B):
import { useReactiveVar } from '@apollo/client'
import { colorVar } from "cache"
// read
const color = useReactiveVar(colorVar)
console.log(color)
// write
colorVar('green')