0

I have some component which is executing some function from api file. For example :

class Modal extends React.Component {
  componentDidMount() {
    this.saveModel();
  }

  saveModel = () => {
    return this.setState({loadingRequest: true}, async () => {
      await Model.graphqlMutation(request).then(() => {
        return this.closeAfterSave();
      });
    });
  }

  render() {
    return <div>Some divs...</div>
  }
}

I am using Apollo Client so I defined my client instance with links

const errorLink = onError(({networkError, graphQLErrors, operation, forward}) => {
  if (graphQLErrors && graphQLErrors[0].message === 'Unauthorized' && localStorage.getItem('authToken')) {
    return promiseToObservable(refreshToken()).flatMap((res) => {
      return forward(operation);
    });
  }
});

const link = ApolloLink.from([
  errorLink,
  authLink,
  batchHttpLink,
]);

export const client = new ApolloClient({
 link,
 cache: new InMemoryCache(),
 defaultOptions: defaultOptions,
});

The problem: in errorLink I am handling errors but I can't pass it down to component which sent request. I would p.ex. display some message. I know React Context API and I did it, connected with my components, but I don't know how to connect to it from client.

Thanks for suggestions.

KKK
  • 61
  • 1
  • 8
  • onError should be used for global error handling. You can access both the data and the errors returned in the response from the object the mutation promise resolves to – Daniel Rearden Dec 10 '19 at 18:59
  • Let's say I have 10 components with same request. I want to store logic for errors for that request in 1 place. – KKK Dec 10 '19 at 19:08
  • You can extract the common logic into a helper function, hook, HOC, etc – Daniel Rearden Dec 10 '19 at 19:10
  • Yeah, so I am trying to place it into `onError` but I can't connect with origin component from there. – KKK Dec 10 '19 at 19:11
  • Right because that's not what onError is meant to be used for – Daniel Rearden Dec 10 '19 at 19:13
  • If it's not `meant to be used for` why apollo client handle this error in `onError` instead of passing down to class or api function? – KKK Dec 10 '19 at 19:20
  • https://stackoverflow.com/questions/59232118/how-to-acess-react-context-from-apollo-set-context-http-link This is not working? – Lasharela Jun 20 '21 at 22:37

0 Answers0