next.js getServerSideProps无法与Apollo一起使用:获取失败

bgtovc5b  于 2023-01-17  发布在  其他
关注(0)|答案(1)|浏览(143)

我尝试从Next.js上的服务器端页面生成页面,但我遇到了一个问题,所以我创建了一个Apollo示例,并从我的查询中导入了一个Query,我从客户端上的apollo传递了变量,就像我在useQuery上所做的那样,因为我不知道另一种方法来做这件事,也不知道如何处理错误?
下面是我的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]),
});

但我得到这个错误:无法获取
下面是它的截图:

abithluo

abithluo1#

这是我的例子,在我的情况下工作。

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

相关问题