I am calling fetchData(url) to retrieve json data. My API data format is like this: PageNo:1 PageSize:100 PageCount:5 TotalRecordCount:600 Items: 0: { ID: 1, SUBJECT: ACC } 1: {…}
My react ItemList.js:
import React, {Component} from 'react';
class ItemList extends Component{
constructor(){
super();
this.state={
Items:[],
hasErrored: false,
isLoading: false
};
}
//retrieve data using fetch
fetchData(url){
this.setState({isLoading: true});
fetch(url)
.then((response)=>{
if (!response.ok){
throw Error(response.statusText);
}
this.setState({isLoading:false});
return response;
})
.then((response)=>{response.Items.json()})
.then((Items)=>{
this.setState({Items});
})
.catch(()=>this.setState({hasErrored:true}));
}
componentDidMount(){
this.fetchData(myURL)
}
render(){
if (this.state.hasErrored){
return <p>There was an error loading the items</p>;
}
if (this.state.isLoading){
return <p>Loading...</p>;
}
return(
<div>
<ul>
{this.state.Items.map((item)=>(
<li key={item.ID}>{item.SUBJECT}</li>
))}
</ul>
</div>
);
}
}
export default ItemList;
It always returns "There was an error loading the items". The Items array is always empty. But if I copy and paste the api url to browser, it works fine. Not sure what is wrong with my code? Thanks.
catchblock. Start from there. Add the error parameter inside thecatch(()=>likecatch((error)=>and check that. Also, you can use inspect element and look at your request inNetworktab.