React – JavaScript component class – How to fetch local data

React

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>
            </>
        );
    }
}
https://www.mldgroup.com

Vyštudovaný top manažér pôsobiaci najmä ako manažér, marketér, softvérový inžinier, konzultant, bloger, YouTuber a zatiaľ neúspešný hudobník a producent. V rámci praxe pôsobil v rôznych odvetviach na rôznych pozíciách v malých aj veľkých firmách, vrátane spoluprác a partnerstiev s významnými firmami či poradenskými spoločnosťami.

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená. Vyžadované polia sú označené *