Reputation: 47
I have placed ErrorComponent on top in the App.js, but it cannot navigate to Home screen. Is there any other way to do this? any guide will be appreciated. I tried How to use navigation.navigate from a component outside the stack.navigation but this doesn't seem to work in my case.
App.js
export class App extends Component {
render() {
return (
<ErrorInterceptor>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<StackNavigation />
</PersistGate>
</Provider>
</ErrorInterceptor>
);
}
}
ErrorInceptor.js
import React, {Component} from 'react';
import {Text, View, TouchableOpacity} from 'react-native';
export default class ErrorInterceptor extends Component {
state = {hasError: false};
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return {hasError: true};
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
// logErrorToMyService(error, errorInfo);
}
changeState = () => {
// console.log('working');
this.setState({hasError: false});
this.props.navigation.navigate('Home');
};
render() {
if (this.state.hasError) {
// console.log(this.props);
// You can render any custom fallback UI
return (
<View>
<Text> Something Went Wrong..! </Text>
<TouchableOpacity
onPress={() => this.changeState()}
style={{width: '40%'}}>
<Text
style={{
backgroundColor: '#898989',
paddingVertical: 10,
borderRadius: 5,
color: 'white',
width: '100%',
textAlign: 'center',
}}>
Return to Home
</Text>
</TouchableOpacity>
</View>
);
}
return this.props.children;
}
}
Upvotes: 2
Views: 1510
Reputation: 56
This is because your error boundary is out of the scope of navigation, and that's the reason you're not able to use navigation props to navigate between screens.
withNavigation from react navigation will also not work here because of the scope. The only thing I think you can do is to create a reference of navigation props on component mount on your root component and set that in your react context or redux store and use it as a ref to access navigation props in your error boundary class.
Upvotes: 4