How to use useQuery and useMutation hooks next to eachother in Next.js

Hello team,

I’m working on a hobby project, with Next.js as frontend and keystone CMS as backend. now Keystone uses GraphQL and Apollo Server to test queries and mutations.

The problem came up when I was trying to implement a Login component in Next.js, which would check the email validity, by searching for it in the backend, before allowing th user to log in. I tried using useQuery. When i use them on their own works fine. But…

Here is my code:

const [ checkEmail, {loading, error} ] = useQuery(EMAIL_CHECK, {
        variables: {
            "where": {
              "email": emailInput
            }
          }
    });

    const [login, { data }] = useMutation(LOGIN, {
        variables: {
            "email": emailInput,
            "password": passwordInput,
        }
    });
    const {name, email, adminRole, userRole, race, races, image, url, authenticateUserWithPassword, item, user} = data || {};

Theres a form i want users to enter their login credentials.

Also, i wanted to declare data inside the useQuery, but i can’t as it is already declared in the useMutation. Now i cant access any data, only from one of the hooks. A mutation returns a token which i need to use setting cookies for the sessions.

What i would like to know is that am I allowed to use useQuery and useMutation in one file or page? Why does this error coming up? How can I solve it?

Any help is appreciated. Thanks

You might want to learn a bit more about how destructuring works in JavaScript. You can rename the destructured variables so they don’t conflict with each other. Here’s some documentation which explains it: Destructuring assignment - JavaScript | MDN

2 Likes