Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. /**
  2. * withData HOC - loads any data as Promise.all, shows loading icon and passes data along via props to children
  3. */
  4.  
  5. import React, { Component } from 'react';
  6. import { Loading } from 'carbon-components-react';
  7. import ErrorModal from '../ErrorModal/ErrorModal';
  8. import RequestUtils from '../../utilities/RequestUtils';
  9.  
  10. /**
  11. * @param {*} WrappedComponent Child React component
  12. * @param {Array} source in form `[{ key: 'string', url: 'string' }, ... ]`
  13. */
  14. const withData = (WrappedComponent, source) => {
  15. class HOC extends Component {
  16. constructor(props) {
  17. super(props);
  18. this.state = {};
  19. }
  20.  
  21. componentDidMount() {
  22. this.loadData();
  23. }
  24.  
  25. loadData() {
  26. const promises = source.map(({ key, url }) => (
  27. RequestUtils.request(url, 'GET')
  28. .then(({ results }) => {
  29. this.setState({
  30. [key]: results
  31. });
  32. }).catch((e) => {
  33. this.showError(`"${url}" ${e.message}`);
  34. throw new Error(`"${url}" ${e.message}`);
  35. })
  36. ));
  37.  
  38. Promise.all(promises).then((v1, v2, v3) => {
  39. console.log('ALL', v1, v2, v3);
  40. this.loadingComplete();
  41. }).catch((e) => {
  42. console.log('error here', e);
  43. });
  44. }
  45.  
  46.  
  47. loadingComplete() {
  48. console.log('loading complete');
  49. this.setState({
  50. loading: false,
  51. error: null
  52. });
  53. }
  54.  
  55. showError(message, e) {
  56. console.log('ERROR', message, e);
  57. this.setState({
  58. loading: false,
  59. error: message
  60. });
  61. }
  62.  
  63. render() {
  64. console.log('here is state data', this.state.data);
  65. if (this.state.loading) {
  66. return <Loading />;
  67. }
  68.  
  69. if (this.state.error) {
  70. return <ErrorModal errorMessage={this.state.error} />;
  71. }
  72.  
  73. return <WrappedComponent {...this.state} />;
  74. }
  75. }
  76.  
  77. return HOC;
  78. };
  79.  
  80.  
  81. export default withData;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement