React lets you build user interfaces out of individual pieces called components. Create your own React components like Thumbnail, LikeButton, and Video. Then combine them into entire screens, pages, and apps.
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. The Fetch API also provides a global fetch()
method that provides an easy, logical way to fetch resources asynchronously across the network.
JSON data location
public/assets/data.json
data.json
{
"test": "done"
}
Example
import { Component } from "react";
export class FetchDemo extends Component {
state = {
data: {},
loaded: false
}
getData() {
let response = fetch("./assets/data.json", {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
return response.then(res => res.json())
}
render() {
if (!this.state.loaded) {
this.getData().then(response => this.setState({ data: response, loaded: true }));
}
return (
<>
<h1>Class component - Fetch demo</h1>
<div>{this.state.data.test}</div>
</>
);
}
}