Fetching WordPress JSON Data Within React

This post will cover how the React application fetches JSON data from the WordPress blog using WordPresses REST api.

Fetching JSON data from within the react application has been made easy by creating a custom fetch function that returns JSON data. The function uses a generic type that can be supplied to provide static type checking. The source code for the described function can be seen in the following screenshot.

The first argument passed into the function is the URL for the request, with the second option being options for the fetch API such as the manual setting of headers, HTTP method or attaching a body to the request. When sending authorization details a header can easily be attached to this function containing the users JWT, retrieving it from the custom AuthContext using the useContext hook. An example of this can be seen within the following code.

The following image provides example usage of the fetchJSON function from the previous screenshot. This page is rendering the page on the server as opposed to the client. This approach was adopted as it prevents the user from seeing a loading screen, as the data is fetched by the server and rendered into HTML before the client retrieves the page.

Fetching JSON data from the WordPress REST api using the functions shown within this post is a streamlined process. By using a custom built function for fetching data the process of converting response data into JSON on every request is automated.

Comments

Popular posts from this blog

WordPress Modifying A Child Theme & Using The OpenWeatherMap API

Creating A WordPress Post Using The REST API

Consuming The WordPress Posts Via The REST API