class MyComponent extends React.Component { constructor(props) { super(props); this.state = { error: null, isLoaded: false, items: [] }; } componentDidMount() { fetch("https://api.example.com/items") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, items: result.items }); }, (error) => { // Note: it's important to handle errors here this.setState({ // instead of a catch() block so that we don't swallow isLoaded: true, // exceptions from actual bugs in components. error }); } ) } render() { const { error, isLoaded, items } = this.state; if (error) { return
Error: {error.message}
; } else if (!isLoaded) { return
Loading...
; } else { return ( ); } }}