0

I've been working on this issue all day on setting up authorisation for my app and realised the issue of this error

Cannot return null for non-nullable field Query.login

Stems from this bit of code here in AuthPage.tsx.

return res.json();

I'm not quite sure the best way to process the data after it's come back from GraphQL (which it's coming back with a 200 response which is great and the information).

This is the full authorisation component called AuthPage.tsx

import React, { Component } from 'react';
import './AuthPage.scss';

export class AuthPage extends React.Component {
    state = {
        isLogin: true
    }

    constructor(props: any) {
        super(props);
        this.emailEl = React.createRef();
        this.passwordEl = React.createRef();
    }

    emailEl: React.RefObject<any>;
    passwordEl: React.RefObject<any>;

    switchModeHandler = () => {
        this.setState((prevState: any) => {
            return {isLogin: !prevState.isLogin}
        })
    }


    submitHandler = (event: any) => {
        event.preventDefault();
        const email = this.emailEl.current.value;
        const password = this.passwordEl.current.value;

        if (email.trim().length === 0 || password.trim().length === 0) {
            return
        }

        let requestBody = {
            query: `
                query {
                    login(email: "${email}", password: "${password}") {
                            userId
                            token
                            tokenExpiration
                    }
                }
            `
        };

        if (!this.state.isLogin) {
            requestBody = {
                query: `
                mutation {
                    createUser(id: "", email: "${email}", password: "${password}") {
                        id
                        email
                        password
                    }
                }
                `
            }
        }

        fetch('http://localhost:4000/graphql', {
            method: 'POST',
            body: JSON.stringify(requestBody),
            headers: {
              'Content-Type': 'application/json'
            }
          })
            .then(res => {
              if (res.status !== 200 && res.status !== 201) {
                throw new Error('Failed!');
              }
              return res.json();
            })
            .then(resData => {
              console.log(resData);
            })
            .catch(err => {
              console.log(err);
            });
        };

    render() {
        return(
            <form className="login" onSubmit={this.submitHandler}>
                <div className="form-control">
                    <label className={"label"} htmlFor={"email"}>Email:</label>
                    <input type="email" placeholder={"Email address"} id={"email"} ref={this.emailEl}/>
                </div>
                <div className="form-control">
                    <label className={"label"} htmlFor={"password"}>Password:</label>
                    <input type="password" placeholder={"Enter password"}  ref={this.passwordEl}/>
                </div>
                <button type={"submit"} className={"button"}>Login</button>
                <button type={"button"} className={"button"} onClick={this.switchModeHandler}>Switch to {this.state.isLogin ? 'Signup' : 'Login'}</button>
            </form>
        )
    }
}

export default AuthPage;

The Schema

module.exports = `
  type User {
    id: ID!
    email: String!
    password: String
  }

  type AuthData {
    userId: ID!
    token: String!
    tokenExpiration: Int!
  }

  input UserInput {
    email: String!
    password: String!
  }

  type Query {
    user(id: String!): User
    users: [User]
    login(email: String!, password: String!): AuthData!
  }

  type RootMutation {
    createUser(userInput: UserInput): User
  }

  type Mutation {
    createUser(id: String, email: String!, password: String!): User
    editUser(id: String, email: String): User
    deleteUser(id: String, email: String): User
  }
`;

My goal is to return the GQL response from the server and format it correctly into a response then return AuthData

but most importantly getting rid of this error Cannot return null for non-nullable field Query.login.

Harry
  • 360
  • 6
  • 19
  • I'm not sure if you can make fetch req and insert queryBody to the request body – Nemer Aug 04 '19 at 22:09
  • because the query or the mutate are graphQL, you could use react-apollo https://www.apollographql.com/docs/react/essentials/queries/ – Nemer Aug 04 '19 at 22:17
  • This is an issue with the resolver for the `login` field and not an issue with your client code. Please refer to [this post](https://stackoverflow.com/questions/56319137/why-does-a-graphql-query-return-null) for debugging help. – Daniel Rearden Aug 05 '19 at 02:40

0 Answers0