2021年4月28日星期三

Authentication flow react native

My app functions in a way that part of the app is visible without logging in, and to view the rest of it, users have to be signed in. My app consists of 2 stacks, the auth stack and the app stack. The auth stack contains the Login and Signup screens. Currently this is the logic of my app. For example, lets say the user goes the to Messages Tab which is only visible is the user is signed in. On MessagesScreen.js, I have the following code.

const [user, setUser] = useState();    useEffect(() => {  console.log('Use effect called');  if (!user) {    fetchUser();    if (!user) {      console.log('THis is called');      navigation.navigate('Auth', {        screen: 'Login',        params: {comingFromScreen: 'Messages'},      });    } else {      console.log(user);    }  }  }, []);    const fetchUser = async () => {  try {    const userData = await getUser();    setUser(userData);  } catch (e) {    console.log('No user found');  }  };  

getUser, is the following function:

export const getUser = async () => {    try {      let userData = await AsyncStorage.getItem('userData');      let data = JSON.parse(userData);    } catch (error) {      console.log('Something went wrong', error);    }  };  

And the LoginScreen consists of the following code:

const handleLogin = () => {      if (email === '' || password === '') {        alert('Email or password not provided');      } else {        firebase          .auth()          .signInWithEmailAndPassword(email, password)          .then((res) => {            storeUser(JSON.stringify(res.user));          })          .catch((e) => alert(e.message));        navigation.navigate('Home', {screen: comingFromScreen});      }    };  

storeUser is the following:

export const storeUser = async (user) => {    try {      await AsyncStorage.setItem('userData', JSON.stringify(user));    } catch (error) {      console.log('Something went wrong', error);    }  };  

When I first navigate to the Messages Screen, the logic works and I get presented with the login screen. But if I click on the 'X' button on the login screen which takes me back to the home screen and then go back to the Messages Screen, I get presented with the screen and moreover, useEffect is not even called.

I'm a little new to react native so can someone tell me what I need to change to achieve my desired effect?

https://stackoverflow.com/questions/67295164/authentication-flow-react-native April 28, 2021 at 02:53PM

没有评论:

发表评论