I wish to add a check to every page in my app. The check is that if a file exists then pull the user to a page.
I think that a HOC is one way to do this (are there others?)
and I have come up with this
import React from "react";import { NavigationScreenProp } from "react-navigation";import RNFS from "react-native-fs";interface MyComponentProps { navigation: NavigationScreenProp<any, any>;}interface MyComponentState {}const importFileCheck = WrappedComponent => { class HOC extends React.Component<MyComponentProps, MyComponentState> { constructor(props) { super(props); this.props.navigation.addListener("didFocus", () => { RNFS.exists(".\path\I\care\about.xml" ).then(exists => { if (exists) { this.props.navigation.navigate("Export"); } }); }); } render() { return <WrappedComponent {...this.props} />; } } return HOC;};export default importFileCheck;
When I run the page I get an error
TypeError: undefined is not an object (evaluating this.props.navigation.addListener)
So I guess that the navigation 'thing' is not being passed through properly
For completion I use the HOC like so
importFileCheck(App)
and App
has the navigation stuff already in it, and works without the HOC.
Imports are
"react": "16.6.1",
"react-native": "0.57.7",
"react-navigation": "3.2.0"
Further details for the keen :D
First I make a stack navigator that is all the pages in my app
const appNav = createStackNavigator( { Calculator: { screen: Calculator, navigationOptions: { title: "Calculator" } }, // more pages);export default createAppContainer(appNav);
In App.tsx
this gets 'wrapped' in other components
const WrappedStack = () => { return <RootStack screenProps={{ t: i18n.getFixedT() }} />;};const ReloadAppOnLanguageChange = translate("translation", { bindI18n: "languageChanged", bindStore: false})(WrappedStack); class App extends React.Component { public render() { return (<I18nextProvider i18n={i18n}><StyleProvider style={getTheme(material)}><Provider ManureStore={ManureStore} SettingsStore={SettingsStore} FieldStore={FieldStore} CalculatorStore={CalculatorStore} FarmStore={FarmStore}><ReloadAppOnLanguageChange /></Provider></StyleProvider></I18nextProvider> ); }}
and finally we wrap with my new HOC
export default importFileCheck(App)