diff --git a/content/docs/faq-ajax.md b/content/docs/faq-ajax.md index cd4cc330..420ac6b7 100644 --- a/content/docs/faq-ajax.md +++ b/content/docs/faq-ajax.md @@ -31,27 +31,35 @@ The example API returns a JSON object like this: ```jsx class MyComponent extends React.Component { - state = { - error: null, - isLoaded: false, - items: [] - }; + 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 - }) + .then( + (result) => { + this.setState({ + isLoaded: true, + items: result.items + }); + }, + // Note: it's important to handle errors here + // instead of a catch() block so that we don't swallow + // exceptions from actual bugs in components. + (error) => { + this.setState({ + isLoaded: true, + error + }); + } ) - .catch(error => - this.setState({ - isLoaded: true, - error - }) - ); } render() { @@ -59,7 +67,7 @@ class MyComponent extends React.Component { if (error) { return
Error: {error.message}
; } else if (!isLoaded) { - return
Loading ...
; + return
Loading...
; } else { return (