Remownz
Remownz

Reputation: 417

Stateful components loosing state on query refetch

Is it correct that stateful components loose their state on a Query component refetch? Do I have to use Apollo client state for all components inside Query components?

Here is a little demo: https://codesandbox.io/s/qxx6jk3yz9 (increase count and then refetch - count will be reset)

Here is the main part of the demo's code:

<ApolloProvider client={client}>
  <div className="App">
    <Query query={GET_ALL_FILMS}>
      {({ data, loading, refetch }) => {
        if (loading) return "Loading...";

        return <Counter refetch={refetch} />;
      }}
    </Query>
  </div>
</ApolloProvider>

Upvotes: 2

Views: 135

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

You have a conditional inside the Query component's render function, namely

if (loading) return "Loading...";

The loading state is updated not just on the initial load, but anytime refetch is called. That means when you hit refetch, only Loading... is rendered and the entire Counter component is unmounted. When the loading state changes back to false, the Counter component is rendered again, but because this is a new component, it starts off with a fresh state.

If you comment out the conditional, you'll see the App behave as you expected.

There's a variety of ways you could approach this problem. Here's three:

  • Manage the state through Apollo, Redux or some other state management library
  • Lift the state up so that it's stored in the Query component's parent component, and then pass the state down to your Counter component, along with a function to mutate it.
  • Instead of not rendering the Counter component, just hide it, for example by setting display to none.

Upvotes: 3

Related Questions