Code icon

REACT - FETCHING DATA FROM API

Links


    //FETCHING DATA FROM API
    //Fetch http requests
    import React from 'react'

    class App extends React.Component { 
    constructor(){
        super()
        this.state ={
            loading: false,
            character: {}
        }
        }

    componentDidMount(){
        this.setState({loading: true})
        console.log("Hi!")
        fetch("https://swapi.dev/api/people/2")
        .then(response => response.json())
        .then(data => {
        this.setState({
            loading: false,
            character: data
        })
        }) 
    }

    render(){
        const text = this.state.loading ? "Loading..." : this.state.character.name
        return (
            <div>
            <p>{text}</p>
            </div>
        )
    }
    }

    export default App;