Skip to content

Instantly share code, notes, and snippets.

@terrysahaidak
Created October 1, 2019 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terrysahaidak/b1fed04887bc77615f204c0f5a154a56 to your computer and use it in GitHub Desktop.
Save terrysahaidak/b1fed04887bc77615f204c0f5a154a56 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { inject } from 'mobx-react';
const RootSpinner = () => <Text>Loading</Text>;
const EmptyCover = ({ retry }) => (
<View>
<Text>Error</Text> <Text onPres={retry}>Retry</Text>
</View>
);
export default function withInitializerFlow(
predicate,
asyncMapper,
SpinnerComponent = RootSpinner,
ErrorComponent = EmptyCover,
) {
return (InnerComponent) => {
class InitializerFlow extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: props.__predicate,
isError: false,
};
this.propsToPass = {};
}
componentDidMount() {
if (this.state.isLoading) {
this.run();
}
}
async run() {
try {
this.setState({ isLoading: true, isError: false });
this.propsToPass = await this.props.__asyncMapper();
this.setState({ isLoading: false });
} catch (err) {
this.setState({ isLoading: false, isError: true });
}
}
render() {
if (this.state.isError) {
return (
<ErrorComponent
{...this.props}
retry={() => this.run()}
/>
);
}
if (this.state.isLoading) {
return <SpinnerComponent {...this.props} />;
}
return (
<InnerComponent {...this.props} {...this.propsToPass} />
);
}
}
const injected = inject((stores, props) => ({
__predicate: predicate(stores, props),
__asyncMapper: () => asyncMapper(stores, props),
}))(InitializerFlow);
return injected;
};
}
export function withNavigationInitializer(
paramsToCheck = [],
asyncFunction,
) {
return withInitializerFlow(
(stores, props) =>
paramsToCheck.some(
(param) =>
typeof props.navigation.getParam(param) !== 'undefined',
),
(stores, props) =>
asyncFunction(stores, props.navigation.state.params, props),
);
}
function Screen({ category }) {
}
const ScreenWithInitializer = withNavigationInitializer(
['category_id'],
async (stores, { category_id }) => {
const category = await stores.entities.categories.getById.run({
category_id,
});
return {
category,
};
}
)(Screen);
EnhancedScreen.navigationOptions = {};
export default EnhancedScreen;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment