Best practices for state management and fetching data
I have been using react-query for a few months now but still feel very green. So I have a Quote component with a bunch of form fields that the user can fill in. I am using that same Quote component for both creating a new Quote and editing an existing Quote because that's the point of React, reuse components. So I am trying to figure out how to handle the react-query state in this case.
So here one of my useQuery functions for the Quote component.
So as I understand it,
selectedPackaging
will be populated with initialSelectedPackaging
if this function is not enabled. And then I just update that state as the user fills in the packaging fields with this code: queryClient.setQueryData( ['quotePackaging', {quoteID: editingQuoteID}],...
Am I understanding that all correctly?9 Replies
correct-apricotOP•12mo ago
And then if it is enabled, it grabs the data from the DB and populates it with that but still allows the user to edit it with
queryClient.setQueryData...
.correct-apricot•12mo ago
seems like you're trying to write to the query cache for temporary form state. Please don't do that. see: https://tkdodo.eu/blog/react-query-and-forms
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.
correct-apricotOP•12mo ago
Its hard for me to see how you're updating local state because this syntax is foreign to me:
correct-apricot•12mo ago
it's from react-hook-form, but it doesn't matter. you can also useState and pass
value
and onChange
the important part is understanding the concept, not the syntaxcorrect-apricotOP•12mo ago
OK, I think that makes sense. So I might have a state field in my form that looks like this:
const [packagingGroup, setPackagingGroup] = useState(selectedPackaging.packagingGroup);
? Where the initial state comes from that useQuery
call above?correct-apricot•12mo ago
if it's a separate component, yes
correct-apricotOP•12mo ago
Awesome! Thank you very much!!
Because if in same component, state updates cause that component to reload and then the useQuery would run all over again, I am assuming.
correct-apricot•12mo ago
no, it's the other way around. if it's the same component, you initialize useState with
undefined
, and then when the data comes in from the query, it won't be reflected in the state because the initial value doesn't sync
I think I covered this in the mentioned article ....correct-apricotOP•12mo ago
That makes sense now. Thanks again!