【问题标题】:How to use GraphQL mutation in Next.js without useMutation如何在没有 useMutation 的情况下在 Next.js 中使用 GraphQL 突变
【发布时间】:2020-08-23 00:44:54
【问题描述】:

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

我得到的错误是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,
});

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

欢迎任何建议, 干杯

【问题讨论】:

    标签: reactjs graphql next.js apollo-client graphql-mutation


    【解决方案1】:

    傻瓜,突变也适用于 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()});
    

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 2020-05-11
      • 2020-05-19
      • 2020-06-11
      • 2023-03-20
      • 2016-01-19
      • 1970-01-01
      • 2020-01-22
      • 2018-10-15
      相关资源
      最近更新 更多