0
votes

I have this problem. In my React Native App after user logs in he gets message from server informing him about the role he has in app (teacher, student) and according to that role different UI is rendered. The thing is my login action is dispatched via Redux(and I am saving some things from response to redux) and I want to navigate to different screens according to that server answer, but I cant navigate from redux action creator. I tried solution from official docs https://reactnavigation.org/docs/navigating-without-navigation-prop/ but I keep getting this error : The 'navigation' object hasn't been initialized yet. Is there any other way to navigate after response from server BUT according to it from redux action? Thank you! My action :

export const loginmyapp = (email, password) => {
  return async dispatch => {
    const response = await fetch(
      'http://147.175.121.250:80/authenticate/login',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          email: email,
          password: password
        })
      }
    );

    if (!response.ok) {
      const errorResData = await response.json();
      console.log(errorResData);
      const errorId = errorResData.error.message;
      let message = 'Something went wrong!';
      if (errorId === 'EMAIL_NOT_FOUND') {
        message = 'Entered email not found!';
      } else if (errorId === 'INVALID_PASSWORD') {
        message = 'Entered password is not valid!';
      }
      throw new Error(message);
    }
    const resData = await response.json();
    console.log(resData);

    dispatch({
      type: LOGINMYAPP,
      token: resData.jwtToken,
      relationId: resData.relationIDd,
      info: resData.info
    });
    RootNavigation.navigate('SignedInZiak');
  };
};

I know that I will be handling down here the response with ifchecks but simply this .navigate doesnt work. Can someone help me please?

1

1 Answers

1
votes

Navigating from redux actions isn't the best way to do it.

I suggest the following :

Add User Reducer with attribute role which is the response from the backend ( teacher or student )

Add Loading Screen ( the initial root in the app after login ) and connect it to user state using mapStateToProps

Add componentDidMount function and check the role of the user and navigate to the screen that you want!