Reputation: 417
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
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:
Query
component's parent component, and then pass the state down to your Counter
component, along with a function to mutate it.display
to none
.Upvotes: 3