Ads Top

how to fetch data from API in react?

Fetch API example in reactjs:

You want to fetch data in the react with API, API stands for application program interface (API). This is the set of the data often data be in the JSON(JavaScript Object Notation) format.  React component life cycle hooks work as when running your project then It’s going to first constructor(), second componentWillMount() third render() and then componentDidMount(). So after rendering the structure then need API. Therefore componentDidMount() is the best place for the API Fetching as given below code.

Your fetching syntax :
componentDidMount(){
        fetch('apriUrl')
        .then(response => response.json())
        .then(result => {
            this.setState({
                isloaded:true    // isloaded should be "false" in the state
                listdata:result  // listdata is an array variable as define in the state
            })
        })
        .catch(error => {
            this.setState({
                isloaded:true
                error       // error should be "null" in the where you define state
            })
        })

    }


fetchdata.js
import React,{Component} from 'react'

export default class FetchData extends Component{
state = {
error : null,
isloaded: false,
listdata : []
}

componentDidMount(){
.then(response => response.json())
.then(
(result) => {
this.setState({
isloaded : true,
listdata : result
})
},
(error) => {
this.setState({
isloaded : true,
error
})
}
)
}

/*
    Also, you can use this code both will working
    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/todos/')
            .then(response => response.json())
            .then(result => {
                    this.setState({
                        isloaded: true,
                        listdata: result
                    })
                })
                .catch(error => {
                    this.setState({
                        isloaded: true,
                        error
                    })
                })
    }*/

renderdata = () => {
return this.state.listdata.map((item, i) => <tr key={i}><td>{item.userId}</td><td>{item.id}</td><td>{item.title}</td><td>{String(item.completed)}</td></tr>)
}

render(){
return(
<> 
<table border="1">
<thead><tr><th>User Id</th><th>Id</th><th>Title</th><th>Completed</th></tr></thead>
<tbody>
{this.renderdata()}
</tbody>
</table>
</>
)
}
}


App.js
import React from 'react';
import './App.css';
import FetchData from './components/fetchdata/fetchdata'

function App() {
return (
<> 
<FetchData/>
</>
);
}

export default App;


No comments:

Copyright Reserved to Anything Learn. Powered by Blogger.