Search code examples
javascriptgraphqlapollo-clientrect

how to login using apollo mutation Graphql login api?


 const LoginQuery = gql`
  mutation {
    login(data: {
      email: "[email protected]",
      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: "[email protected]",
      password: "Imagine100!"
  
    })
  } 
`;

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

then getting error this as enter image description here


Solution

  • 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: "[email protected]",
        password:  "Imagine100!"
      }
    });
    console.log('response -- ', response);
    

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