My code below works, I used optional chaining to load information from the API. I was trying to get it to work by checking the loading state or checking if the array was empty, but I didn't have success. When I searched for "React API optional chaining", I didn't find much information specifically for these cases. The code below works, but is the way I did this considered okay? What other ways can I use to do this? What is the best way?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
loading: true
}
}
componentDidMount() {
fetch('https://restcountries.eu/rest/v2/all')
.then(response => response.json())
.then(json => this.setState({data: json}));
this.setState({loading: false});
}
render() {
return (
<div>
<h1>{this.state.data?.length > 0 && this.state.data[0]["name"]}</h1>
</div>
)
}
}
export default App;