,

Part 7 of the Next.js Tutorial: Fetching Posts from WordPress GraphQL API

Posted by








Next.js Tutorial – How to Fetch Posts from WordPress GraphQL API [part 7]

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.


0 0 votes
Article Rating
16 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Shinyu ja
7 months ago

Thank You For Tutorial 🥰

Sunjay Armstead
7 months ago

Thank you so much for this video / series! Very easy to follow and extremely informative.

jyoti chabba
7 months ago

Hi @codeReflections graphql is not fetching all posts. Is there anything we can modify?

Celso Sá
7 months ago

Thanks for the videos, helped me alot ♥

Boris Barzotto
7 months ago

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

Djortinho
7 months ago

Wonderful explanation. Easy to follow along

Pratik Vishwakarma
7 months ago

graphl me cursor ke through new next js docs pr kese pagiantion banye

Lalit Kumar
7 months ago

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

wheezeTV
7 months ago

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&quot;, {

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

}

}

}

`,

};

Мария Троянова
7 months ago

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

David Essien
7 months ago

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.

Gabriel Araujo
7 months ago

Thanks for the video. How would it be with pagination? 🤔

Sherwin Anos
7 months ago

Awesome bro, thanks for the tutorial 🙂

Huxlygerard Singh
7 months ago

Please update the next video waiting eagerly for it

R. Ramos
7 months ago

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!

Ivan G
7 months ago

Thanks for the video update. What window manager do you use?