local state of the api data
I get some data from the api using useQuery but I need to modify it until I hit the save button (same as a form but it's not). Is it a good practice to use setQueryData to update the data and then call useMutation with the modified data in the cache
For instance:
I get an array thanks to useQuery, I add an element with my form
setQueryData((oldArray) => [...oldArray, 'new element'])
and then when I hit the save button I call my api with the data present in the cache?
Do you see any downside to this solution, should I either create a local state to store the modified array and not update the query cache?
Thank you !5 Replies
genetic-orangeOP•11mo ago
tell me if it's not clear or if you need a playground
optimistic-gold•11mo ago
React Query and Forms
Forms tend to blur the line between server and client state, so let's see how that plays together with React Query.
genetic-orangeOP•11mo ago
so it's a bad practice to do something like this? https://codesandbox.io/p/devbox/affectionate-hermann-6823nm?file=%2Fsrc%2Findex.jsx%3A31%2C25
one question about your article, what if I'm not using useState but I want to use a context and pass the query data as initial data of the context data. To achieve this it's not as easy as doing useState(queryData) because it's a context. In that case I will need a useEffect or use the deprecated onSuccess of useQuery. Am I missing something?
optimistic-gold•11mo ago
React Query and React Context
Can it make sense to combine React Query with React Context ? Yes, sometimes ...
genetic-orangeOP•11mo ago
If I understand well, in my case, since I'm working with a form and because forms can be an exception to the rule "don't copy state from tanstack to local state" I could wrap my "form" with a context and provide some function that update the context without changing the query cache and get the 2 data out of sync, right?