Tuesday, September 22, 2020
therichposts@gmail.com
ReactjsRest Api Wp

Reactjs fetch data from wordpress

Reactjs fetch data from wordpress

Hello, welcome to therichpost.com. In this post, I will tell you, Reactjs fetch data from wordpress. Reactjs is a Javascript Library to build user interface.

This is data coming from wordpress in reactjs app index.html file:

reactjs-fetch-data-wordpress-api

In this post, I will tell you, how to fetch data from wordpress(wordpress user) with reactjs. In my app, we will use react js as frontend and wordpress as backend.

Here is working and tested code for Reactjs fetch data from wordpress and you just need to add this into your reactaApp App.jsx file:
import React from 'react';

class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("http://localhost/cfood4u/wp-json/wp/v2/getusers")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result
          });
      
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }
   render() {
   
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {items.map((item)=><li>{item}</li>)}
        </ul>
      );
    }
  }
}
export default App;

 If you have any query related to this post, then please comment below.

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, Angular 8, Angular 9, Angular 10 Nodejs, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.