TanStackT
TanStack3y ago
5 replies
thick-teal

Safely setting store state based on query data/status

We have a main grid component that is effectively the most important component in our app - the entire rest of the UI depends on knowing when it's loading, has data/is empty, etc.

We're using a zustand store to hold a few basic pieces of information, but we need to set this information based on the results and status of the react query.

However, we can't directly set the store values in the below example because on initial render that would trigger the dreaded react error "Cannot update a component while rendering a different component"

Our approach is wrong here, so I'm curious on what the recommended way of handling this would be. Wrapping the setXYZ code in
useEffect
works but I don't think that's a valid solution here, just a bandaid.

The setXYZ code really should just be called on the first success event and then any time a refetch begins after that, but I've always hated having some kind of initial state boolean and hope there's a better way


const MainGrid = () => {
  const { data, isFetching } = useQuery(...)

  setMainGridIsReady(!isFetching)
  setMainGridIsEmpty(!data?.length)

  return <Grid .../>
}
Was this page helpful?