I'm trying to write a React Native Functional Component that simply checks some values within a Redux state, and depending on that result immediately re-routes the user to the correct screen.
If I send the wrong routeName to the navigate function, it will throw an error stating that it couldn't find the route. But when I pass a routename that exists, then it will just do nothing.
I can verify 100% that navigation and wizard have the proper data for this to work. Any ideas what I'm missing here? Thanks in advance!
import React, { useEffect } from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
const SetupLoader = ( props:any ) => {
const { navigation, wizard } = props;
let setupRoute = '';
useEffect(() => {
// HANDLE CASE OF MID-REGISTRATION
if (!wizard.step1) {
setupRoute = 'Step1';
}
if (!wizard.step2) {
setupRoute = 'Step2';
}
else {
setupRoute = 'Dashboard';
}
navigation.navigate(setupRoute);
},[]);
return (
<View></View>
)
}
const mapStateToProps = ( state:any ) => ({
wizard: state.wizard
});
export default connect(mapStateToProps)(SetupLoader);
Thanks in part to Wen, I was able to get it to work. I tied the redirect route name into a state variable. useEffect then updates that variable and on the second pass through useEffect, navigation is called and the screen re-routes correctly.
import React, { useEffect, useState } from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
const SetupLoader = (props: any) => {
const { navigation, wizard } = props;
const [route, setRoute] = useState('');
useEffect(() => {
if (route === '') {
let setupRoute = '';
if (!wizard.step1) {
setupRoute = 'Step1';
}
else if (!wizard.step2) {
setupRoute = 'Step2';
}
else {
setupRoute = 'Dashboard';
}
setRoute(setupRoute);
} else {
navigation.replace(route);
}
}, [ route ]);
return (
<View></View>
)
}
const mapStateToProps = (state: any) => ({
wizard: state.wizard
});
export default connect(mapStateToProps)(SetupLoader);