Search code examples
graphqlapollo

Retry to fetch on GraphQLError


Hello folks I came across on graphql errors and I would like to know if there is a way to handle the error by showing an alert to retry refetching the query.

so in a short example I have the following

renderError() {
  Alert.alert(
    'ERROR',
    'There is a problem!',
    [
      { text: 'Try again', onPress: () => console.log('refetch query') },
      {
        text: 'Cancel',
        onPress: () => console.log('Cancel'),
        style: 'cancel',
      },
    ],
    { cancelable: false },
  );
}

render() {
  if(loading){
    return <Loader loadVisible={loadingVisible} animationType="fade" />;
  } else if (error){
    return <View>{this.renderError()}</View>;
  } else {
    ... 
  }
}

Solution

  • According to the documentation in Apollo Queries you can access a refetch() function from the render prop pattern.

    The same way you have loading, error and data you can use refetch and then you just have to pass it and call it in the event you need.

    Something like:

    renderError(refetch) {
      Alert.alert(
        'ERROR',
        'There is a problem!',
        [
          { text: 'Try again', onPress: () => refetch() },
          {
            text: 'Cancel',
            onPress: () => console.log('Cancel'),
            style: 'cancel',
          },
        ],
        { cancelable: false },
      );
    }
    
    render() {
      if(loading){
        return <Loader loadVisible={loadingVisible} animationType="fade" />;
      } else if (error){
        return <View>{this.renderError(refetch)}</View>;
      } else {
        ... 
      }
    }