T
TanStack•3y ago
useful-bronze

how would you do this without the useQuery's onSuccess callback?

I'm using useQuery to fetch data for a table. The row data has a category field. I want to add a filter so the user can toggle the display of rows in certain categories. Prior to this major change talk i would reach for the onSuccess to set some filter state.
onSuccess: (data) => {
const categoryState: Record<string, boolean> = {}
for (const row of data) {
// toggle all categories on by default
categoryState[row.category] = true
}
setCategoryState(categoryState)
}
onSuccess: (data) => {
const categoryState: Record<string, boolean> = {}
for (const row of data) {
// toggle all categories on by default
categoryState[row.category] = true
}
setCategoryState(categoryState)
}
Would you change this to useEffect? Or just change the filter logic to only check for categories explicitly set to false so undefined would mean "on" as well?
const isFooCategoryOn = categoryState.foo !== false
const isFooCategoryOn = categoryState.foo !== false
4 Replies
rare-sapphire
rare-sapphire•3y ago
not at all.
rare-sapphire
rare-sapphire•3y ago
sorry, I just read the title 🙈 There are two ways: - split it up in two components - use derived state going into details here: 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.
rare-sapphire
rare-sapphire•3y ago
it's "form" related because you basically want to set an "initial state" for your form (checkboxes / filters), but asynchronously react-hook-form also has a values api that is reactive for this case if you're using RHFa
useful-bronze
useful-bronzeOP•3y ago
i think splitting it up into two components is the way to go. thanks!

Did you find this page helpful?