I am new to Redux and I don't understand what is wrong with the following set up. I got error: TypeError: TypeError: undefined is not an object (evaluating 'this.props.navigation.navigate')
For actions, I have a function for login:
export const loginWithEmail = ({email, password}) => async (dispatch) => {
dispatch({type: "LOADING"})
try {
let user = await auth.signInWithEmailAndPassword(email, password);
dispatch({type: "LOGIN_SUCCESS", payload: user})
} catch (error) {
dispatch({type: "LOGIN_FAILURE"})
}
}
Login component:
class Login extends Component {
componentWillReceiveProps(nextProps) {
if(!_.isEmpty(nextProps.user)) {
this.props.navigation.navigate('Home');
}
}
login() {
const {email, password} = this.props;
this.props.loginWithEmail({email, password});
}
render() {
return (
...
)
}
}
const mapStateToProps = state => {
return {
email: state.auth.email,
password: state.auth.password,
error: state.auth.error,
user: state.auth.user
}
}
export default connect(mapStateToProps, {loginWithEmail})(Login);
In my App.js
const AuthStack = createStackNavigator({
Login: { screen: Login }
});
const MainStack = createStackNavigator(
{
Home: { screen: 'Home' },
Auth: AuthStack
},
{
initialRouteName: 'Home'
}
);
const AppContainer = createAppContainer(MainStack);
export default class App extends React.Component {
constructor(props) {
super(props);
}
render() {
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return (
<Provider store={store}>
<AppContainer/>
</Provider>
);
}
}
I did also try to use the Login component in another component like this:
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return (
...
<Provider store={store}>
<Login navigation={this.props.navigation}/>
</Provider>
My react-navigation version is 3.2.1
Update: tried following the solution from React Native: TypeError: undefined is not an object (evaluating 'this.props.navigation.navigate') but no success
It's because of the other file where you are using Login screen component directly.
<Provider store={store}>
<Login/>
</Provider>
This will not if you are expecting this.props.navigation
to have a value. The solution here would be to remove this other use of Provider
.
The following that you have already is enough to connect to Redux.
<Provider store={store}>
<AppContainer/>
</Provider>