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.