useQuery and useEffect (Possible Anti-Pattern)
Hi there - I have a particular pattern I've been using in my React/Next codebase. It feels a bit like an anti-pattern, but I'm not sure the best way to adjust my code.
Right now, when I have a "details" page, or some page where you can view and edit an object, the component is structured something like this:
- data fetching is done using react-query to retrieve the object in question. for example, we are fetching an associate by their ID, pulled from the page params
- for each editable attribute, we have a useState, and any edits made by the user are set into this
- whenever the data changes, we have a useEffect that manually sets all of the useStates to the value of the data (because data is fetched asynchronously)
- in the actual TSX, it's a basic form with radix ui components
- the submit button calls a mutation that pulls data from the useStates
I think the useEffect is probably not necessary, or at the very least it feels wrong. Right now it's needed because the data is initially undefined, and I want to populate "defaults" of the pseudo-form/page. Is this wrong? and if so, what is a better approach? I appreciate any tips - thanks!
4 Replies
like-gold•16mo ago
Yeah check out tkdodo query form
like-gold•16mo 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.
absent-sapphireOP•16mo ago
ahh nice. Seems like TkDodo has an article for everything 😅 thanks
conscious-sapphire•16mo ago
I really do 😂