ReactiveVar doesn't cause hook to update if updated in a separate function
See original GitHub issueHello! I was working with reactiveVars, following along with https://youtu.be/xASrlg9rmR4?t=957 the issue may be that I, like the video, was creating a reactiveVar in the cache, rather than just on its own. But here is what I ran into: I have my reactive var, and I made a function to update that reactive var (like the video demonstrates with delete-todo)
i have a button that, when clicked, calls that function to update the reactive var, and i display the value of that var with useReactiveVar
however it doesn’t update
Intended outcome: when i call the addColor function, it should update the reactiveVar, and that should in turn cause a re-render because my page refers to the value changed by it
Actual outcome: calling addColor does seem to update the var, but that doesn’t trigger a re-render on the useReactiveVar hook
How to reproduce the issue: https://codesandbox.io/s/use-reactive-var-no-update-nh75m?file=/src/App.tsx
cacheModel.ts
export const cacheMoney: InMemoryCache = new InMemoryCache({
/// other cache settings
});
export const initialUserSettingsVar = cacheMoney.makeVar<UserSettings>(initialUserSettings);
export function addColor(userSettingsVar: ReactiveVar<UserSettings>) {
return (newColor = 'green') => {
//get latest value of the settings
const currVal = userSettingsVar();
//update the color
currVal.favoriteColor = newColor;
//set the new value
userSettingsVar(currVal);
};
}
MyComponent.tsx
export const QueryPage = () => {
const otherSettingsData = useReactiveVar(initialUserSettingsVar);
return (
<>
<Button
onClick={() => {
addColor(initialUserSettingsVar)(); //why doesn't this work?
// initialUserSettingsVar({ ...initialUserSettingsVar(), favoriteColor: 'blue' }); //this works
}}
>
Add Color
</Button>
<div>Fav Color: {otherSettingsData.favoriteColor} </div>
)
}
Versions apollo-client “latest” (yarn lock says 3.3.11)
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (2 by maintainers)
Top GitHub Comments
@benjamn btw, we’ve been using reactiveVars on our team for a few months now and they’re AWESOME way easier than redux and even easier than React Context. yall should be shouting about these on the rooftops. even for folks not even calling a GraphQL backend
@madmaxlax The root value that you store in the reactive variable has to change for any notifications to happen, so this code
needs to modify
currVal
somehow, rather than mutating its contents: