Emanuela Ianc
Emanuela Ianc

Reputation: 77

How to use GraphQL mutation in Next.js without useMutation

I'm working on a codebase with Next.js version 9.3.0 and GraphQL. To get the benefits of Next.js optimizations, we are wrapping each page in withApollo, so inside the pages we can make use of useQuery, useMutation. The issue I'm facing is that I need to use mutation in the Header component which is outside the page, which doesn't have access to ApolloClient because the app is not wrapped in withApollo.

The error I'm getting is this Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance in via options.

The Header component is inside the Layout component like this:

<>
   <Meta />
   <Header/>
   {children} // pages which are composed with withApollo
   <Footer />
</>

Instead of using useQuery in a component without withApollo is easy you can use

import { createApolloFetch } from 'apollo-fetch';

const fetch = createApolloFetch({
    uri: process.env.GRAPHQL_SERVER,
});

const userInfoQuery = `{
    userInfo {
        loggedIn
        basketCount
        wishListCount
    }
}`;

const userInfoData = fetch({
      query: userInfoQuery,
});

Is there an alternative solution for useMutation in a component not composed with withApollo?

Any suggestions are welcomed, Cheers

Upvotes: 4

Views: 3968

Answers (1)

Emanuela Ianc
Emanuela Ianc

Reputation: 77

Silly me, mutations work with Apollo fetch too

https://github.com/apollographql/apollo-fetch#simple-graphql-mutation-with-variables but this is not maintained anymore

The solution that worked for me, in the end, was to still useMutation and to pass the client to it. https://www.apollographql.com/docs/react/data/mutations/#usemutation-api

import { useMutation } from '@apollo/react-hooks';
import createApolloClient from 'lib/apolloClient';
import loginUser from 'mutations/login';

const [getToken, { data: mutationData, error: loginErrors, loading }] = useMutation(loginUser, { client: createApolloClient()});

Upvotes: 3

Related Questions