So I've been trying to convert a part of react app into react-native. In react I had a user login and saved all of users info into a localStorage. Here's a piece of code:
userActions.js:
dispatch({
type: USER_LOGIN_SUCCESS,
payload: data,
});
AsyncStorage.setItem("userInfo", JSON.stringify(data));
store.js:
const userInfoFromStorage = localStorage.getItem("userInfo")
? JSON.parse(localStorage.getItem("userInfo"))
: null;
const initialState = {
userLogin: { userInfo: userInfoFromStorage },
};
LoginPage.jsx:
// redirect to register
const redirect = location.search ? location.search.split("=")[1] : "/";
const userLogin = useSelector((state) => state.userLogin);
const { loading, error, userInfo } = userLogin;
useEffect(() => {
if (userInfo) {
history.push(redirect);
}
}, [history, userInfo, redirect]);
Now the question is how do I do this in react-native? Tried this way but it doesn't seem to work:
userActions.js:
dispatch({
type: USER_LOGIN_SUCCESS,
payload: data,
});
AsyncStorage.setItem("userInfo", JSON.stringify(data));
store.js:
const userInfoFromStorage = AsyncStorage.getItem('userInfo')
const initialState = {
userLogin: { userInfo: userInfoFromStorage },
};
In store.js in the react-native project I tried parsing it, but it throws an error with react-native, so my guess AsyncStorage does that automatically?
And now usually when I start the application it logs in automatically (not sure if the user is correct, because I cannot see it).
Login.screen.jsx:
const userLogin = useSelector((state) => state.userLogin);
const { loading, error, userInfo } = userLogin;
useEffect(() => {
if (userInfo) {
navigation.navigate("Main", { screen: "Orders" });
}
}, [userInfo, navigation]);
const submitHandler = (e) => {
dispatch(login(email, password));
console.log('login')
};
But also, if I logout, nothing happens and I cannot log back in. Unless I restart the application, then it logs the user back in automatically.
This is also logout action:
userActions.js:
export const logout = () => (dispatch) => {
// localStorage.removeItem("userInfo");
// this is where I'm trying to change from localStorage to Async on logout, but it doesn't seem to be doing anything
AsyncStorage.removeItem("userInfo");
dispatch({ type: USER_LOGOUT });
dispatch({ type: USER_DETAILS_RESET });
// dispatch({ type: ORDER_LIST_MY_RESET });
dispatch({ type: USER_LIST_RESET });
};
Any help is appreciated. Thank you.