Guest User

Untitled

a guest
Jan 19th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. class DynamicData extends Component {
  2. state = {
  3. loading: true,
  4. error: null,
  5. data: null
  6. };
  7.  
  8. componentDidMount () {
  9. fetchData(this.props.id)
  10. .then((data) => {
  11. this.setState({
  12. loading: false,
  13. data
  14. });
  15. })
  16. .catch((error) => {
  17. this.setState({
  18. loading: false,
  19. error: error.message
  20. });
  21. });
  22. }
  23.  
  24. componentDidUpdate (prevProps) {
  25. if (this.props.id !== prevProps.id) {
  26. this.setState({ loading: true }, () => {
  27. fetchData(this.props.id)
  28. .then((data) => {
  29. this.setState({
  30. loading: false,
  31. data
  32. });
  33. })
  34. .catch((error) => {
  35. this.setState({
  36. loading: false,
  37. error: error.message
  38. });
  39. });
  40. });
  41. }
  42. }
  43.  
  44. render () {
  45. const { loading, error, data } = this.state;
  46. return loading ? (
  47. <p>Loading...</p>
  48. ) : error ? (
  49. <p>Error: {error}</p>
  50. ) : (
  51. <p>Data loaded 🎉</p>
  52. );
  53. }
  54. }
Add Comment
Please, Sign In to add comment