Next.js Tutorial – How to Fetch Posts from WordPress GraphQL API [part 7]
Welcome to part 7 of our Next.js tutorial series. In this tutorial, we will learn how to fetch posts from a WordPress site using the GraphQL API and render them in a Next.js application.
Prerequisites
In order to follow along with this tutorial, you’ll need the following:
- Basic knowledge of React and Next.js
- A WordPress site with the WPGraphQL plugin installed and configured
- A Next.js application set up and running
Fetching Posts from WordPress using GraphQL
First, we need to install the `@apollo/client` package in our Next.js application. We can do this by running the following command in the terminal:
npm install @apollo/client graphql
Next, we can create a new file called `apolloClient.js` and configure our Apollo client to connect to the WordPress GraphQL API:
import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";
import { setContext } from '@apollo/client/link/context';
const httpLink = createHttpLink({
uri: 'https://your-wordpress-site.com/graphql',
});
const authLink = setContext((_, { headers }) => {
const token = process.env.WORDPRESS_AUTH_TOKEN;
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
export default client;
Now that our Apollo client is set up, we can create a new component called `PostList` to fetch and render the posts:
import { useQuery, gql } from '@apollo/client';
const POSTS_QUERY = gql`
query {
posts {
nodes {
id
title
content
}
}
}
`;
function PostList() {
const { loading, error, data } = useQuery(POSTS_QUERY);
if (loading) return Loading...
;
if (error) return Error: ${error.message}
;
return (
<div>
<h2>Posts</h2>
<ul>
{data.posts.nodes.map(post => (
<li key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</li>
))}
</ul>
</div>
);
}
export default PostList;
Rendering the PostList component in our Next.js application
Finally, we can import and render the `PostList` component in our Next.js pages:
import PostList from '../components/PostList';
function Home() {
return (
<div>
<h1>Welcome to my WordPress Blog</h1>
<PostList />
</div>
);
}
export default Home;
And that’s it! We have successfully fetched and rendered posts from our WordPress site using the GraphQL API in our Next.js application.
Thank You For Tutorial 🥰
Thank you so much for this video / series! Very easy to follow and extremely informative.
Hi @codeReflections graphql is not fetching all posts. Is there anything we can modify?
Thanks for the videos, helped me alot ♥
Hi @CodingReflections how i can get the featured image in original quality? whats the setting for that, i only get a sourset of bad quality images, you can get a good image in node position [0], i get a random set of images and different sizes, random order too
Wonderful explanation. Easy to follow along
graphl me cursor ke through new next js docs pr kese pagiantion banye
Hello sir I am getting undefined while fetching the data and also in the postman I am getting a cloud agent error. Is there anything I need to enable in the wordpress. I would massively appreciate it if you could help me with this. Thanks
my solution:
stack: wpgraphql 1.14.3, wordpress 6.2 next 13.3
page/blog:
const [posts, setPosts] = useState();
useEffect(() => {
async function getPosts() {
const response = await fetch("http://localhost/wp-blogwithnext/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(queryAllPost),
});
const data = await response.json();
setPosts(data);
}
getPosts();
}, []);
<Article posts={posts} /> // This would be the children of the page blog
posts.js:
export const queryAllPost = {
query: `
query getShort {
posts {
nodes {
date
slug
title
excerpt
}
}
}
`,
};
graphics-ide does not load, an error appears in the console. "Uncaught (in promise) GraphQLError: Names must only contain [_a-zA-Z0-9] but "Template_An empty "does not." Please help me solve this error
Hi @CodingReflections This is the most straightforward video on this topic I have seen so far. I have been trying to get this right since last year, but nothing was making sense to me. You just made everything clear. Thank you.
Is it possible for you to do this with Typescript and maybe the code gen? That would really be helpful.
Thanks for the video. How would it be with pagination? 🤔
Awesome bro, thanks for the tutorial 🙂
Please update the next video waiting eagerly for it
Thank you so mu h for this tutorial, exactly what I was needing to study some specific NextJS stuff alongside with WordPress! 😄
Suggestion: saw the overview video and it didn't include the comment section, using mutation and other stuff needed. Saw very few videos showing it, but solely outside WordPress (with Apollo and other CMS (GraphCMS, for example), which made me a bit confusing about how to apply it using WPGraphQL)… nothing about comments with WPGraphQL at all. Would you consider adding it to the final product, please? Already read the documentation, but had a tough time trying to make it work. 🙁
Thank you so much in advance!
Thanks for the video update. What window manager do you use?