Reputation: 12064
I have graphql Query as follows:
<Query query={GET_COMPANY_ADDRESSES} variables={{companyId: session.company.id}} notifyOnNetworkStatusChange={true} fetchPolicy={'cache-and-network'}>
{({loading, error, refetch, data}) => {
if (loading) return <LoadingIndicator/>;
if (error) return <ErrorIndicator description={error.message}/>;
const address = data.companyAddresses[1];
return (
<React.Fragment>
<CollapsiblePanel title="Add slot">
<SlotForm address={address} toggleSlotForm={this.toggleSlotForm.bind(this)} refetch={refetch}/>
</CollapsiblePanel>
</React.Fragment>
)
}}
</Query>
I show there an loading indicator
on initial load. It works fine. But I have form inside <SlotForm />
component where I can add record to the database. The submit function of the form as follows:
handleSaveSlot({address}, data) {
const slot = {
...data,
address: address.id
};
return client.mutate({
variables: {input: slot},
mutation: ADD_NEW_SLOT,
})
.then(result => {
if (result.data.createSlot.ok) {
this.props.refetch();
this.setState({hasError: false, errorMessage: "", saved: true, slot: initialSlot()}, () => {
setTimeout(() => this.props.toggleSlotForm(false), 3000)
});
}
})
.catch(error => {
let error_msg = error.message.replace("GraphQL error: ", '');
this.setState({hasError: true, saved: false, errorMessage: error_msg});
throw(error_msg);
});
}
After response in .then
I'm refetching the data with this.props.refetch();
. But when refetch is executed I get the loading indicator again before the data is updated on the screen.
I want to avoid that and I do not want to show loading indicator
every time when I add a new record. I just want to show it on initial load.
Every time when I refetch the data I want to do that "in background" without showing loading indicator.
Any idea how to do that?
Upvotes: 2
Views: 2336
Reputation: 84687
It should be sufficient to change your conditional like this:
if (loading && !data.companyAddresses) {
return <LoadingIndicator/>;
}
data.companyAddresses
will be undefined until your initial query is complete, but should be defined even when you trigger a refetch.
If possible, you should also consider using the update
option with your Mutation
component, rather than refetching the query. Updating your cache manually after a mutation is typically better than refetching since it's faster and reduces network load. See the docs for more details.
Upvotes: 1