From b1d64dc8a299bacd96f5ec540b22f3262ff93dda Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Sun, 12 Nov 2017 20:04:10 -0800 Subject: [PATCH] Handle more states in async example code --- content/docs/faq-ajax.md | 56 ++++++++++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 20 deletions(-) diff --git a/content/docs/faq-ajax.md b/content/docs/faq-ajax.md index 511f0a9a..5dd852e0 100644 --- a/content/docs/faq-ajax.md +++ b/content/docs/faq-ajax.md @@ -31,30 +31,46 @@ The example API returns a JSON object like this: ```jsx class MyComponent extends React.Component { - constructor(props) { - super(props) - this.state = { - isLoaded: false, - error: null, - items: [], - } - } - + state = { + error: null, + isLoaded: false, + items: [] + }; + componentDidMount() { - fetch('https://api.example.com/items') + fetch("https://api.example.com/items") .then(res => res.json()) - .then(result => this.setState({items: result.items)) - .catch(err => this.setState({ err: error })) + .then(result => + this.setState({ + isLoaded: true, + items: result.items + }) + ) + .catch(error => + this.setState({ + isLoaded: true, + error + }) + ); } - + render() { - const {error, items} = this.state - if (err) return
{error}
- return ( - - ) + const { error, items } = this.state; + if (error) { + return
Error: {error.message}
; + } else if (!isLoaded) { + return
Loading ...
; + } else { + return ( + + ); + } } } ```