T
TanStack•3y ago
rare-sapphire

Sync between local state (in useReducer) and db for a form builder

I am building a form builder. Since it is a fairly complex data structure to store the form template state, I am using a reducer to store the local state so that updates can be made modularly. The initial state for this reducer is gotten from react-query. However, when there is an update to a field, I want it to update in the db onBlur (rather than a save button). I am not sure if what I'm doing makes sense - 1. When there is a change (let's say the name of the form for simplicity), I locally change the state of the input and onBlur I change the reducer state with a dispatch. 2. The dispatch also has a mutation which makes the api call to update the db. I am not sure how the reducer state and react-query state stay in sync though. Does the initial value being updated (passed via props from react-query) also update the reducer state and keep it in sync?
2 Replies
xenial-black
xenial-black•3y ago
If react-query is only used to fetch the initial form data, do you have to keep it updated? Since you then manage the changes in local state, you could use react query just to set the initial values and then ignore it in favour of the local state.
foreign-sapphire
foreign-sapphire•3y ago
Hi 👋 What is it exactly that you're trying to synchronise? It sounds like you're only using TanStack Query to fetch the initial form data and then perform mutations - this doesn't seem like something you'd synchronise

Did you find this page helpful?