简体   繁体   中英

How do you do server side rendering with nextjs [id].js in headless wordpress? fetch single page using graphql from Wordpress. like service/[id].js

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 hooks to fetch my data from the backend, and the react hooks prevents me from calling my backend inside of the getServerSideProps.
Create and fetch single page using graphql from Wordpress with clean URLs like services/[id].js NB: Warning Show ( Error: Response not successful: Received status code 500)

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

  export const client = new ApolloClient({
    uri: 'https://.........../graphql',
    cache: new InMemoryCache()
  });

const serviceDetail = (serviceOutput) => {
    return (
            <div>
                {serviceOutput.serviceTitle}
                {serviceOutput.serviceContent}
            </div>
    )
}

export const getServerSideProps = async (context) => {
    const result = await client.query({
        query: gql` 
              query serData($id: id!) {
                HomePage: pageBy(uri: "https://......./home/") {
                aboutSection {
                    serviceSec(id: $id) {
                        id
                        serviceTitle
                        serviceContent
                        serviceImage {
                            sourceUrl
                        }
                    }
                }
                }
              }
            `,
        variables: {
          id: context.params.id
      }
    })

    return {
        props: {
            serviceOutput: result.data.HomePage.aboutSection.serviceSec;
        },
    };
}

export default serviceDetail;

i am not an expert, but as far i have used. you cannot use Apollo together with next.js fetching method(ssg,ssr,isr).

Apollo runs queries on client side, and can be used with useQuery and useLazyQuery. while next.js fetching is completely different.

I will demonstrate 2 ways here.

-- Using Apollo --

const FETCH_ALL = gql`
  query MyQuery($first: Int!, $after: String) {
    posts(first: $first, after: $after) {
      edges {
        node {
          title
        }
      }
    }
  }
`;

export default function LoadMoreList() {
  const { data } = useQuery(FETCH_ALL, {
    variables: { first: 5, after: null },
    notifyOnNetworkStatusChange: true,
  });
return (
    <>
      <div>
        {postdata.map((node, index) => {
          {
            return (
              <div key={index}>
                <h1>{node?.node?.title}</h1>
              </div>
            );
          }
        })}
      </div>
     </>
)}

=== using fetch and getStaticProps ==

--File1 (this is a fetch function, to which you pass your queries and variables)

async function fetchAPI(query, { variables } = {}) {
  const headers = { "Content-Type": "application/json" };

  const res = await fetch(process.env.WP_API, {
    method: "POST",
    headers,
    body: JSON.stringify({ query, variables }),
  });

  const json = await res.json();
  if (json.errors) {
    console.log(json.errors);
    throw new Error("Failed to fetch API");
  }

  return json.data;
}
export default fetchAPI;

-- File2 (this is a file that contains your query)

import fetchAPI from "./fetching";

export async function homeheadposts() {
  const data = await fetchAPI(
    `
      query homeheadposts {
        posts(first: 7) {
            edges {
                node {
                    id
                    slug
                    title
                    featuredImage {
                        node {
                            sourceUrl
                         }
                    }
                    excerpt(format: RAW)
                }
            }
        }
    }
`
  );

  return data?.posts;

}

-- File3 (place this function, where you wanna call and use the data, )

    export async function getStaticProps() {
      const latestPosts = await homeheadposts();
      return {
        props: { latestPosts },
      };
    }
export default function CallingData({ latestPosts }) {
  console.log(latestPosts);
  return <h1>hello</h1>;
}

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