Maramal
Maramal

Reputation: 3466

Cannot handle error in React ApolloClient

I am trying to compare a real world application using this Authentication server example where I fetch some data from this. But I am not being able to catch client errors since Apollo Client send its own exception to the console.

My sample server compares inputs and "database" user and password and send back a string response or throw an error if there is no matches.

This is my frontend code:

import React from "react";
import ReactDOM from "react-dom";
import ApolloClient, { gql } from "apollo-boost";

import "./styles.css";

class App extends React.Component {
  state = {
    username: "",
    password: "",
    message: ""
  };
  render() {
    return (
      <div className="App">
        <form onSubmit={this.submitForm.bind(this)}>
          <h1>Login</h1>
          <div className="formControl">
            <label htmlFor="username">
              Username&nbsp;
              <input
                id="username"
                value={this.state.username}
                onChange={this.changeInput.bind(this)}
              />
            </label>
          </div>
          <div className="formControl">
            <label htmlFor="password">
              Password&nbsp;
              <input
                id="password"
                value={this.state.password}
                onChange={this.changeInput.bind(this)}
              />
            </label>
          </div>
          <button>Login</button>
        </form>
        <p>{this.state.message}</p>
      </div>
    );
  }

  changeInput(e) {
    this.setState({ [e.target.id]: [e.target.value] });
  }

  async submitForm(e) {
    e.preventDefault();
    const client = new ApolloClient({
      uri: "https://5fbqp.sse.codesandbox.io/graphql"
    });

    const CHECK_USER = gql`
      query {
        login(user: "${this.state.username}", pass: "${this.state.password}")
      }
    `;
    const { data, error, loading } = await client.query({ query: CHECK_USER });
    // The following lines are being completely ignored.
    if (loading) this.setState({ message: "Validating credentials" });
    if (error) this.setState({ message: error });
    if (data) console.log(data);
    console.log("Done");
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I have tried different ways to achieve and seems that this NPM package is the "best solution" to consume GraphQL APIs.

I have also read a lot about error handling with this package but I am not sure how to apply to this project. In my real world example I use Context API to manage authentication.

Any comments to achieve error handling or anything else are appreciated.

Upvotes: 0

Views: 46

Answers (1)

Maramal
Maramal

Reputation: 3466

I just made it work changing default value of errorPolicy inside query() function to 'all' according to Apollo React documentation - Error handling like:

const CHECK_USER = gql`
    query {
        login(user: "${this.state.username}", pass: "${this.state.password}")
    }
`;
const { data, error, loading } = await client.query({ 
    query: CHECK_USER,
    errorPolicy: 'all'
});

It shows the same error in the Developer Tools console but now it allows the app to keep running on error.

Upvotes: 1

Related Questions