Jul
26
2019

For last almost 15+ years now, WordPress runes on the internet and in the current status WordPress runs almost one-third in the web world. According to W3Techs WordPress Powers 34%  of all the websites on the internet, including those without a content management system (CMS) or with a custom-coded CMS.

WordPress Development uses PHP for all its backend infrastructure like updates, APIs, auth, DB layer and most of the frontend. However, like other popular frameworks, WordPress has also been forced to evolve in recent times.

The WP REST API attempts to bridge the gap between the legacy of WordPress’s PHP core and rise of JavaScript. I believe that this is a huge step for WordPress for some reasons:

  •  Existing WordPress websites can use React/ Vue or another frontend library to create a better UI experience.
  • Web Developers get an industry standard Headless CMS that can be easily integrated with the stack of their choice.

Headless CMS

  • Let me explain what is Headless CMS first. You may hear the buzz word “Headless CMS” if you’ve searched for an easy way to manage content for your React js project. Because this term is becoming more popular, it may be beneficial to define that sooner rather than later.
  • By default, WordPress uses theme and template structure which provide a front-end for our WordPress sites.
  • Building a site like this uses to interact with the database and create structure our users can view.

WordPress Rest API basics 

  • The WP REST API packs a batter in every up-to-date installation,  by providing a built-in API that can be integrated into themes, mobile applications, and many more. In other words, we can say like It enables developers to separate the front end interface from data management, letting any application interact with WordPress.

The End Points

  • WordPress endpoints are very accessible to the public. If you’re running the latest version of WordPress, you need to simply append /wp-json/wp/v2 to the end of the URL. For instance, you can access the basic endpoints at wordpress/wp-json/wp/v2 if you’ve set up a WordPress instance in your localhost. If you want to prettify the output, you can use a JSON viewer extension that makes the JSON look pretty on your browser.
  • heme developers, as well as plugin developers, can create custom endpoints for their application. If you want to check out all the different endpoints available, you can download an application like Postman. This will provide you with a GUI specially made for exploring APIs. Moreover, you can directly make API calls to third-party apps without having to rely on plugins. 
  • If you want to learn more about End Points then you can check below link.
    > https://developer.wordpress.org/rest-api/

 

Now Let’s Started with React 

  • React is a declarative front-end library for building user interfaces and interactive applications on the web. With React JS Development, you can compose smaller independent pieces of reusable code known as components. Let’s create our first component by creating a React project.
  • The most popular way to create a React project is by running create-react-app. CRA offers a comfortable environment for learning React and is the best way to start building a new single-page application if you’re a beginner. It sets up your development environment so that you can use the latest JavaScript features such as ES6, and web pack. Moreover, create-react-app provides a nice developer experience and optimizes your app for production.
  • To fetch external data in JavaScript, you need to use promises. This will likely have implications for the way you want to structure your React components, and in my case (converting an existing React project), I had to re-write a fair amount of code.

Promises in JavaScript

  • Promises in JavaScript are used to handle asynchronous actions — things that happen outside the usual step-by-step or “synchronous” order of execution (after hoisting).
  • The good news is that asynchronous JavaScript is a lot easier than it used to be. Before ES6, we were dependent on callback functions. If multiple callbacks were necessary (and they often were), nesting would lead to code that was very difficult to read, scale and debug — a phenomenon sometimes known as callback hell, or the pyramid of doom!
  • Promises were introduced in ES6 (or ES2015) to solve that problem, and ES8 (or ES2018) saw the introduction of async … await , two keywords which further simplify asynchronous functionality. But for our purposes, the most critical promise-based method is fetch() .

The Fetch Method

  • This method has been available since Chrome 40, and it is an easier-to-use alternative to XMLHttpRequest() .

fetch() returns a promise and so it is “then-able”, meaning that you can use the then()method to process the outcome.

You can add fetch to a method inside your React class component, like so:

fetchPostData(){  fetch(`http://localhost/yoursitename/wp-json/wp/v2/movies?per_page=100`)  .then(response => response.json()) .then(myJSON => { // Logic goes here});}
In the code above, two things are important:

  • First, we are calling a URL with the filter ?per_page=100 appended onto the end. By default, WordPress only shows 10 items per page, and I often find myself wanting to increase that limit.
  • Second, before processing our data, we are using the .json() method. This method is used primarily in relation to fetch(), and it returns the data as a promise and parses the body text as JSON.
  • In most cases, we’ll want to run this function as soon as our React component has mounted, and we can specify this using the componentDidMount() method:
  • componentDidMount() {  this.fetchPostData();}

Handling Promises

  • Once you have returned a promise, you have to be careful about handling it in the correct context.
  • When I first tried to use promises, I spent a while trying to pass that data to variables outside of the scope of the promise. Here are a few rules of thumb:
  • In React, the best way to use promises is via the state. You can use this.setState() to pass promise data into your component’s state.
  • It is best to process, sort and re-arrange your data within a series of then()methods following the initial fetch() . Once any processing is complete, it is best practice to add the data to state within your final then() method.
  • If you want to call any additional functions to process your promise (including within render()) it’s good practice to prevent the function from running until the promise has resolved.
  • So, for example, if you’re passing your promise to this.state.data, you can include a conditional within the body of any functions that depend on it, like below. This can prevent annoying unwanted behavior!

myPromiseMethod() {  if (this.state.data) {    // process promise here } else {    // what to do before the fetch is successful  }}
A Working Example in React

Let’s say we want to pull in the name, description, featured_image, and genre of the custom WordPress post type we defined in part 1.

In the following example, we’ll fetch those four elements for each movie and render them.

As so often with React tutorials, the following block of code may look intimidating, but I hope it will seem much simpler when we break it down.

constructor(props)

  • In this method, we call super(props), define our initial state (an empty data object) and bind three new methods:
  • fetchPostData()
  • renderMovies()
  • populatePageAfterFetch()

componentDidMount()

  • We want to fetch our data as soon as the component has mounted, so we’ll call fetchPostData() in here.

fetchPostData()

  • We fetch the JSON from our URL, passing .json() in the first .then() method.
  • In the second .then() method, we extract the four values we want for every movie entry we’ve fetched and then add them to our newState object.
  • We then use this.setState(newState) to add this information to this.state.data .

renderMovies()

  • The conditional if (this.state.data) means that the function will only run once data has been fetched.
  • In here, we take an array of all our fetched movies from this.state.data and pass it to the function populatePageAfterFetch() .

populatePageAfterFetch()

  • In this function, we prepare the data for each movie to be rendered. This should look straightforward to anyone who’s used JSX, with one potential stumbling block.
  • The value of movie.description is not plain text, but HTML markup. To display this, we can use dangerouslySetInnerHTML={{__html: movie.description}} .

render()

Finally, we control where our rendered data will appear by calling the renderMovies()method within our chosen <div> tags. We’ve now successfully fetched data from our WordPress site and displayed it!