how to login using apollo mutation Graphql login api?

Viewed 54
 const LoginQuery = gql`
  mutation {
    login(data: {
      email: "cherineewong@gmail.com",
      password: "Imagine100!"
  
    })
  } 
`;

This is my graphql login api mutation code I don't get any response. geting error like this Invariant Violation: Running a Query requires a graphql Query, but a Mutation was used instead. I'm also use query keyword like this,

  const LoginQuery = gql`
  query mutation {
    login(data: {
      email: "cherineewong@gmail.com",
      password: "Imagine100!"
  
    })
  } 
`;

const { loading, error, data } = useQuery(LoginQuery);
console.log(data)

then getting error this as enter image description here

2 Answers

You should use apollo's useMutation hook

import { useMutation } from "@apollo/client"

export const LOGIN_MUTATION = gql`
    mutation Login($email: String!, $password: String) {
       login(input: { email: $email, password: $password }) {
          message // ... the keys which you expecting in response from the server.
         
       }   
    } 
`

const [submitLogin] = useMutation(LOGIN_MUTATION);

Then you can use the handle login method like this

const response = await submitLogin({ variables:
  { 
    email: "cherineewong@gmail.com",
    password:  "Imagine100!"
  }
});
console.log('response -- ', response);

For Reference https://www.apollographql.com/docs/react/api/react/hooks/#usemutation

Related