3

我正在使用Next.js版本 9.3.0 和GraphQL. 为了获得 Next.js 优化的好处,我们将每个页面包装在 中withApollo,因此在页面内部我们可以使用useQuery, useMutation。我面临的问题是我需要在Header component页面外部使用突变,ApolloClient因为应用程序未包含在withApollo.

我得到的错误是这个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.

Header组件在组件内部,如下Layout所示:

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

而不是在没有useQuery的组件中使用很容易,您可以使用 withApollo

import { createApolloFetch } from 'apollo-fetch';

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

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

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

useMutation在不是由 组成的组件中是否有替代解决方案withApollo

欢迎任何建议,干杯

4

1 回答 1

2

愚蠢的我,突变也适用于 Apollo fetch

https://github.com/apollographql/apollo-fetch#simple-graphql-mutation-with-variables但这不再维护

最后,对我有用的解决方案是静止useMutation并将客户传递给它。 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()});
于 2020-05-07T17:47:34.897 回答