...

/

Understanding How Components Access the Backend Web API

Understanding How Components Access the Backend Web API

Learn to understand how the React frontend consumes the backend web API.

We'll cover the following...

The final topic we’ll cover in this segment is how the React frontend consumes the backend web API. If the app isn’t running, then run it by pressing “F5” in Visual Studio. If we click the “Fetch data” option in the top navigation bar in the app that opens in the browser, we’ll see a page showing weather forecasts:

Press + to interact
Weather forecast data
Weather forecast data

If we cast our minds back to earlier in this chapter, in the Understandingcontrollers section, we looked at an ASP.NET Core controller that surfaced a web API that exposed the data at weatherforecast. So, this is a great place to have a quick look at how a React app can call an ASP.NET Core web API.

The component that renders this page is in FetchData.js. Let’s open this file and look at the constructor class:

Press + to interact
constructor (props) {
super(props);
this.state = { forecasts: [], loading: true };
}

The constructor class in a JavaScript class is a special method that automatically gets invoked when a class instance is created. So, it’s a great place to initialize class-level variables.

The constructor initializes a component state, which contains the weather forecast data, and a flag to indicate whether the data is being fetched. We’ll learn more ...