简体   繁体   中英

How do you do server side rendering with nextjs if you have apollo react hooks to fetch data from backend?

I have a nextjs project that is using apollo graphql to fetch data from the backend. I am trying to render my page using server side rendering. But I am currently using graphql apollo react hooks to fetch my data from the backend, and the react hooks prevents me from calling my backend inside of the getServerSideProps.

How do I solve this issue?

import * as React from "react";
import { useExampleQuery } from "graphql/types";

export const getServerSideProps = async ({ params }) => {
  // Here we should probably call graphql function that is now called inside Page
  return { props: { hash: params.hash } };
};

const Page = ({ hash }) => {
  /* 
    I am currently calling my graphql query here using apollo react hooks, 
    that are generated inside graphql/types using @graphql-codegen (typescript)
  */
  const { data, loading } = useExampleQuery({
    variables: {
      hash: hash,
    },
  });

  return loading ? <p>{loading}</p> : <p>{data.example.text}</p>;
};

export default Page;

getServerSideProps is a server-side function so you can't quite call the apollo query hooks inside it.

An approach is to use the apollo client instance query method.

See the example code below.

import { gql } from '@apollo/client';
import apolloClient from '/path/to/graphql/server/client';

// Example Query
const EXAMPLE_QUERY = gql`
  query EXAMPLE_QUERY($hash: String!) {
    exampleQuery(hash: $hash) {
      ...
    }
  }
`;

export const getServerSideProps = async ({ params }) => {
  const { data } = await apolloClient.query({
    query: EXAMPLE_QUERY,
    variables: { hash: params.hash },
  });

  return {
    props: {
      hash: params.hash,
      data,
    },
  };
};

Also, if importing your apollo client server instance is a bit unclear, you can use this graphql-request package for making graphql requests given a URL.

See example

import { GraphQLClient } from "graphql-request";

// Replace GRAPHQL_URL below to actual
const client =  new GraphQLClient(<GRAPHQL_URL>);

export const getServerSideProps = async ({ params }) => {

  const { data } = await client.request(EXAMPLE_QUERY, {
      hash: params.hash 
  });

  return {
    props: {
      hash: params.hash,
      data,
    },
  };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM