|
| 1 | +// @ts-ignore |
| 2 | +import React, { Component, Fragment } from "react"; |
| 3 | +import { connect } from "react-redux"; |
| 4 | +import { bindActionCreators } from "redux"; |
| 5 | + |
| 6 | +import { fetchModels, modelsCreators } from "../../store/actions"; |
| 7 | +import { Spinner, FetchError, SyncBtn222 } from "../../components/elements"; |
| 8 | +import { getModelsErrorState, getModelsState } from "../../store/selectors"; |
| 9 | +import { ErrorBoundary } from "../index"; |
| 10 | +import ui from "../../helpers/libs/ui"; |
| 11 | +import dal from "../../helpers/libs/dal"; |
| 12 | + |
| 13 | +const { setModelsFromLocalStorage } = modelsCreators.getFunctions(); |
| 14 | + |
| 15 | +interface IProps { |
| 16 | + modelsList: any; |
| 17 | + fetchModels: () => void; |
| 18 | + setModelsFromLocalStorage: () => void; |
| 19 | + errorMsg: any; |
| 20 | +} |
| 21 | + |
| 22 | +function WithModels(WrappedComponent) { |
| 23 | + class Wrap extends Component<IProps> { |
| 24 | + componentDidMount() { |
| 25 | + const { |
| 26 | + modelsList, |
| 27 | + fetchModels, |
| 28 | + setModelsFromLocalStorage, |
| 29 | + errorMsg, |
| 30 | + } = this.props; |
| 31 | + |
| 32 | + !modelsList && |
| 33 | + ui.getData({ |
| 34 | + item: "models", |
| 35 | + setFunc: setModelsFromLocalStorage, |
| 36 | + fetchFunc: fetchModels, |
| 37 | + }); |
| 38 | + |
| 39 | + dal.setSync({ error: errorMsg, funcForCall: fetchModels }); |
| 40 | + } |
| 41 | + |
| 42 | + componentDidUpdate(prevProps) { |
| 43 | + const { modelsList } = this.props; |
| 44 | + |
| 45 | + ui.updateLocal({ |
| 46 | + list: modelsList, |
| 47 | + prevList: prevProps.modelsList, |
| 48 | + item: "models", |
| 49 | + }); |
| 50 | + } |
| 51 | + |
| 52 | + render() { |
| 53 | + const { modelsList, errorMsg, fetchModels } = this.props; |
| 54 | + |
| 55 | + if (errorMsg) { |
| 56 | + return ( |
| 57 | + <Fragment> |
| 58 | + <FetchError err={errorMsg} /> |
| 59 | + <SyncBtn222 syncNow={fetchModels} /> |
| 60 | + </Fragment> |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + if (!modelsList) { |
| 65 | + return <Spinner />; |
| 66 | + } |
| 67 | + |
| 68 | + return ( |
| 69 | + <ErrorBoundary cgildren={""}> |
| 70 | + <WrappedComponent {...this.props} /> |
| 71 | + </ErrorBoundary> |
| 72 | + ); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + const mapStateToProps = (state) => ({ |
| 77 | + modelsList: getModelsState(state), |
| 78 | + errorMsg: getModelsErrorState(state), |
| 79 | + }); |
| 80 | + |
| 81 | + const mapDispatchToProps = (dispatch) => |
| 82 | + bindActionCreators({ fetchModels, setModelsFromLocalStorage }, dispatch); |
| 83 | + |
| 84 | + return connect(mapStateToProps, mapDispatchToProps)(Wrap); |
| 85 | +} |
| 86 | + |
| 87 | +export { WithModels }; |
0 commit comments