#Headless Wordpress/NextJS app not returning blog posts

13 messages · Page 1 of 1 (latest)

lofty shale
#

I have two files src/app/lib/api.js which has the following:

const API_URL = process.env.WORDPRESS_API_URL;

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

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({ query, variables }),
  });

  const json = await res.json();
  if (json.errors) {
    console.log(json.errors);
    console.log('error details', query, variables);
    throw new Error('Failed to fetch API');
  }
  return json.data;
}

export async function getAllPosts(preview) {
  const data = await fetchAPI(
    `
    query AllPosts {
      posts(first: 20, where: {orderby: {field: DATE, order: DESC}}) {
        edges {
          node {
            date
            id
            slug
            title
            content
          }
        }
      }
    }
    `
  );

  return data?.posts;
}

My API_URL is defined in .env and in my environmental variables from the Graphql Wordpress plugin...

Then I built a component to house the api call and to display the blog posts app/src/(components)/Wordpress.js

'use client';
import { getAllPosts } from '../lib/api';

const Wordpress = ({ allPosts }) => {
  // Check if allPosts and edges are defined before accessing their properties
  const edges = allPosts ? allPosts.edges : [];

  return (
    <section>
      {edges.map(({ node }) => (
        <div key={node.id}>
          <p className='text-3xl font-cursive text-black'>
            {node.title}
          </p>
        </div>
      ))}
    </section>
  );
};

export default Wordpress;

export async function getStaticProps() {
  const allPosts = await getAllPosts();

  return {
    props: {
      allPosts,
    },
  };
}

I am not getting any errors in production or development but when I put the Wordpress component into a test page it just creates an empty div

I am not sure why the node.title is not populating. The query is returning results at the Wordpress GraphiQL IDE.

fickle sandalBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

lofty shale
#

I also tried this in the (component)/Wordpress.js

import { getAllPostsForHome } from '../lib/api';

export default function Wordpress({ allPosts, preview }) {
  const post = allPosts && allPosts.edges[0]?.node;

  return (
    <div preview={preview}>
      {post && (
        <div>
          <div title={post.title}>
            {/* Other properties */}
          </div>
        </div>
      )}
    </div>
  );
}

half urchin
#

look like you are using app router

#

which doesn't have getStaticProps

#

call the getAllPosts function directly in your page component and pass the data to Wordpress component

dawn sand
#

I’m a next.js developer and have many years of experience and have connected to wpgraphql many times

lofty shale
half urchin
#

the getStaticProps only execute on pages

#

so move it to index.js then pass the data the <Blog />

#

export default function Home({ allPosts }) {}

#

<Blog allPosts={allPost} />

lofty shale