Guest User

Untitled

a guest
Jan 20th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. const DataContext = React.createContext();
  2.  
  3. class DataContextProvider extends Component {
  4. // We want to be able to store multiple sources in the provider,
  5. // so we store an object with unique keys for each data set +
  6. // loading state
  7. state = {
  8. data: {},
  9. fetch: this.fetch.bind(this)
  10. };
  11.  
  12. fetch (key) {
  13. if (this.state[key] && (this.state[key].data || this.state[key].loading)) {
  14. // Data is either already loaded or loading, so no need to fetch!
  15. return;
  16. }
  17.  
  18. this.setState(
  19. {
  20. [key]: {
  21. loading: true,
  22. error: null,
  23. data: null
  24. }
  25. },
  26. () => {
  27. fetchData(key)
  28. .then((data) => {
  29. this.setState({
  30. [key]: {
  31. loading: false,
  32. data
  33. }
  34. });
  35. })
  36. .catch((e) => {
  37. this.setState({
  38. [key]: {
  39. loading: false,
  40. error: e.message
  41. }
  42. });
  43. });
  44. }
  45. );
  46. }
  47.  
  48. render () {
  49. return <DataContext.Provider value={this.state} {...this.props} />;
  50. }
  51. }
  52.  
  53. class DynamicData extends Component {
  54. static contextType = DataContext;
  55.  
  56. componentDidMount () {
  57. this.context.fetch(this.props.id);
  58. }
  59.  
  60. componentDidUpdate (prevProps) {
  61. if (this.props.id !== prevProps.id) {
  62. this.context.fetch(this.props.id);
  63. }
  64. }
  65.  
  66. render () {
  67. const { id } = this.props;
  68. const { data } = this.context;
  69.  
  70. const idData = data[id];
  71.  
  72. return idData.loading ? (
  73. <p>Loading...</p>
  74. ) : idData.error ? (
  75. <p>Error: {idData.error}</p>
  76. ) : (
  77. <p>Data loaded 🎉</p>
  78. );
  79. }
  80. }
Add Comment
Please, Sign In to add comment