【问题标题】:NextJs: getServerSideProps is not working with Apollo: fetch failedNextJs:getServerSideProps 不适用于 Apollo:获取失败
【发布时间】:2023-01-09 22:30:00
【问题描述】:

我正在尝试从 Next.js 上的服务器端页面生成页面,但我遇到了问题,所以我创建了一个 Apollo 实例,并从我的查询中导入了一个 Query,然后我像在useQuery 上一样从客户端的 apollo 传递变量,因为我不知道另一种方法,也不知道如何处理这个错误?

这是我的getServerSideProps

export async function getServerSideProps(context) {
  const slug = context.params.slug;

  const data = await Static.query({
    query: LANDING,
    variables: { slug },
  });

  return {
    props: {
      data: data,
    },
  };
}

这是我的查询:

import gql from "graphql-tag";

export const CATEGORIES = gql`
  query CategoriesView {
    CategoriesView {
      _id
      Name
      Description
      Icon
    }
  }
`;

这是我的客户:

import {
  ApolloClient,
  HttpLink,
  ApolloLink,
  InMemoryCache,
} from "@apollo/client";

const uri = "http://localhost:3000/api"

const httpLink = new HttpLink({uri});

export const Apollo = new ApolloClient({
  ssr: typeof window === "undefined" ? true : false,
  cache: new InMemoryCache(),
  link: ApolloLink.from([httpLink]),
});

但我收到此错误:无法获取

这是它的屏幕截图:

【问题讨论】:

    标签: next.js apollo


    【解决方案1】:

    这是我的例子,在我的案例中工作。

    import { useSubscription, useQuery, gql } from "@apollo/client";
    import { serverSideTranslations } from "next-i18next/serverSideTranslations";
    
    //your query here ; first check if your query works (use your playground)
    const QUERY = gql`
        query {
            customers{
                data{
                    attributes{
                        firstname
                        lastname
                        location
                        phone
                        createdAt
                    }
                }
            }
        }
    `;
    
    
    const Page = () => {
        //apollo function
      const { data, loading, error } = useQuery(QUERY);
    
      if (loading) return <div>Loading...</div>
      if (error) return <div>Failed to load!</div>
    
      return (
        <>
          {JSON.stringify(data)}
        </>
      )
    };
    
    //can do with staticProps, serverProps, etc. Below just an example - delete if not needed
    export async function getStaticProps({ locale }) {
      return {
        props: {
          ...(await serverSideTranslations(locale, ["common"])),
        },
      };
    }
    
    export default Page;
    

    我不确定您是否可以将 gql 查询放在 getServerSideProps 中,因为 apollo 会为您的查询创建某种“缓存”。

    并检查@apollo/client图书馆

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 2019-11-27
      • 2020-08-11
      • 2020-09-28
      • 1970-01-01
      相关资源
      最近更新 更多