0

I have problem with displaying pagination. I'm using Wordpress REST API to fetch my posts Here is my code:

import React, { Component } from "react";
import "./App.css";

class App extends React.Component {
 constructor() {
        super();
        this.state = {
          items: [],
          totalPages: '',
          nextPage: '',
        };
        this._loadData = this._loadData.bind(this);
      }
      componentDidMount() {
        const url = 'http://localhost/wp-json/wp/v2/';
        this._loadData(url);

      }
      _loadData(url) {
        request.get(url).then((response) => {
          this.setState({
            items: response.body.items.data,
            totalPages: response.body.items.last_page,
            nextPage: response.body.items.next_page_url
          });
        });
      }
      render() {
        let items = _.map(this.state.items, (item) => {
        return (
                <div key={item.id}>
                        <div className="content">
                            <span>
                                {item.type}
                            </span>

                        </div>
                </div>
        )
    });
        return (
            <div>
               {items}
            </div>

            <div>
               <a href="#0" onClick={this._loadData(this.state.nextPage)}/>Next
            </div>
      }
}

export default App;

I need help beacuse I can not figure out where the problem is. I would appreciate some tutorial or something like that.

mijok
  • 201
  • 2
  • 13
  • What is _loadData for? Is it a function or is it a particular syntax for react? –  Jun 19 '20 at 10:45

1 Answers1

0

Your WordPress's REST API Endpoint isn't correct.

When you fetching data from http://localhost/wp-json/wp/v2/ using GET method, it will returns only the namespaces and routes.

If you would like to pull posts or pages, should use path like this. http://localhost/wp-json/wp/v2/{post_type}

Replace {post_type} with the post type in plural word.

For example you would like to get latest posts you should request to

http://localhost/wp-json/wp/v2/posts

Also you can preview this url in your browser.

  • Ohh thank you @weerayut-teja, now I have problem Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment? But everything seems fine to me. See image https://ibb.co/kVK39f – mijok Nov 19 '18 at 14:55
  • Yes, JSX will required some tag to wrap the render content. This is example: https://stackoverflow.com/a/33385872/1061169 – Weerayut Teja Nov 19 '18 at 15:01