Sync local state with cache

Hi everyone. I need some help and may be recommendation on how to sync local state with cached one. For example i have a controlled input component which gets it’s initial state value from cache. When I will enter some text to the input it will update local state and send debounced updates (mutate data) to the server from where I get a response and update the cache. When cache is updated input component must react on the changes and decide whether it should update local state with the cached one, because debounced update can return old state when user continue editing or cache can be updated from some other place.

Hi @Oberin98 :wave: welcome to the community forum! Just so I’m certain I understand the question, would you mind if I listed the requirements?

Given a controlled input component instance Input and a local field named foo:

  1. Input should reflect the value foo stored in InMemoryCache unless there is a more recent local update initiated by the user
  2. Input should always show the most recent user-modified value for foo unless there is a newer value that was edited locally in the cache (do not supercede user input with an update from a mutation initiated via Input)
  3. When the user changes Input, the updated value for foo is sent as a mutation to a graph and updated in InMemoryCache as part of the same operation (debounced). The result of the mutation should not be reflected in Input

Is that accurate?

If so, there are several design choices available but one I would not recommend is passing foo directly into Input e.g. <Input value={foo} />. Instead, consider centralizing your three-way merge logic into a different function, maybe a hook that wraps useState. In that hook you could encapsulate the logic for all these decision trees. I hope that helps move the conversation forward!

Hi @JeffAuriemma. Thanks a lot for your response.
Yes, thats what i meant, sorry for my English.

By rising this question, I was hoping that there was already some code implementation to keep local state in sync with the cached one and vice versa. I’ve already implemented this functionality in a separate hook where I rely on the updatedAt field of the incoming from the cache value. But there are still problem cases in this implementation.