Last active
January 20, 2019 02:51
-
-
Save julianburr/2ab30be942268ca86d4ac016de85abc5 to your computer and use it in GitHub Desktop.
Why Suspense Will Be a Game Changer - Local State
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DynamicData extends Component { | |
state = { | |
loading: true, | |
error: null, | |
data: null | |
}; | |
componentDidMount () { | |
fetchData(this.props.id) | |
.then((data) => { | |
this.setState({ | |
loading: false, | |
data | |
}); | |
}) | |
.catch((error) => { | |
this.setState({ | |
loading: false, | |
error: error.message | |
}); | |
}); | |
} | |
componentDidUpdate (prevProps) { | |
if (this.props.id !== prevProps.id) { | |
this.setState({ loading: true }, () => { | |
fetchData(this.props.id) | |
.then((data) => { | |
this.setState({ | |
loading: false, | |
data | |
}); | |
}) | |
.catch((error) => { | |
this.setState({ | |
loading: false, | |
error: error.message | |
}); | |
}); | |
}); | |
} | |
} | |
render () { | |
const { loading, error, data } = this.state; | |
return loading ? ( | |
<p>Loading...</p> | |
) : error ? ( | |
<p>Error: {error}</p> | |
) : ( | |
<p>Data loaded 🎉</p> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment