UNPKG

2.66 kBJSXView Raw
1// @flow
2
3import * as React from "react";
4
5type LoadDataItemPropTypes = {
6 isFetching: bool;
7 fetched: bool;
8 id: string;
9 hasError: bool;
10 data: any;
11 children: React.Node;
12 shouldFetch: any;
13
14 fetchItem: () => void;
15};
16
17type OwnProps = {
18 id: string;
19 settings: {
20 selectors: any;
21 dataItemURL: string;
22 endpoint: string;
23 manageEntity: any;
24 normalizeDataItem: any;
25 }
26};
27
28import { withRouter } from "react-router-dom";
29import { connect } from "react-redux";
30
31import { fetchItem as fetchItemAction } from "./actions";
32
33import { LargeErrorMessage, LoadingMessage } from "x25/Messages";
34
35const
36 mapStateToProps = (state : any, { settings : { selectors }, id } : OwnProps) => ({
37 data : selectors.getItem(state, id),
38 hasError : selectors.getItemHasError(state, id),
39 fetched : selectors.getItemIsFetched(state, id),
40 isFetching : selectors.getIsFetchingItemInfo(state, id),
41 shouldFetch : selectors.getShouldFetchItemInfo(state, id),
42 }),
43 mapDispatchToProps = (dispatch : any, { id, settings } : OwnProps) => ({
44 fetchItem () {
45 dispatch(fetchItemAction({
46 ...settings,
47 id,
48 }));
49 },
50 });
51
52class LoadDataItem extends React.Component<LoadDataItemPropTypes> {
53 props: LoadDataItemPropTypes;
54
55 UNSAFE_componentWillMount () {
56 const { shouldFetch, fetchItem } = this.props;
57
58 if (shouldFetch) {
59 fetchItem();
60 }
61 }
62
63 shouldComponentUpdate (nextProps : LoadDataItemPropTypes) {
64 return (
65 this.props.data !== nextProps.data ||
66 this.props.hasError !== nextProps.hasError ||
67 this.props.fetched !== nextProps.fetched ||
68 this.props.isFetching !== nextProps.isFetching ||
69 this.props.shouldFetch !== nextProps.shouldFetch ||
70 this.props.id !== nextProps.id
71 );
72 }
73
74 UNSAFE_componentWillReceiveProps (nextProps) {
75 const { shouldFetch, fetchItem } = nextProps;
76
77 if (shouldFetch) {
78 fetchItem();
79 }
80 }
81
82 render () {
83 const { children, data, isFetching, hasError, fetchItem } = this.props;
84
85 if (isFetching) {
86 return (
87 <LoadingMessage message="Preiau datele..." />
88 );
89 }
90
91 if (hasError) {
92 return (
93 <LargeErrorMessage
94 message="Ceva nu a mers bine"
95 onRetry={fetchItem}
96 />
97 );
98 }
99
100 if (data.size === 0) {
101 return null;
102 }
103
104 return (
105 <React.Fragment>
106 {children}
107 </React.Fragment>
108 );
109 }
110}
111
112
113export default withRouter(connect(mapStateToProps, mapDispatchToProps)(LoadDataItem));