Remember me with redux storage

Viewed 1540

I have userDetails in redux store and I used redux persist with redux storage to save the details after loads page or after closing my app.

The problem is, when I logged in and I don't checked the rememberMe in index.js is checked if !rememberMe and do logOut() right after login.

So I need to check just at the entrance into the app for the first time and if !rememberMe I will call logOut() but if userDetails !== 'emepty' && rememberMe I will do login() for get valid token.

Why I need to check this it in the first time? because I need to reset the uesrDetails to guest details if !rememberMe.

This is my index.js:

const setBeforeLists = useCallback(
    (lists) => {
        beforeListsChanged(lists);
    },
    [beforeListsChanged]
);

const setUserDetails = useCallback(
    (userDetails) => {
        userDetailsChanged(userDetails);
    },
    [userDetailsChanged]
);

useEffect(() => {
//userDetails.id === 'empty' is guest.
   if (
        userDetails.id !== 'empty' &&
        !userDetails.rememberMe
        ) {
            logOut(setUserDetails, setBeforeLists);
        }
    }, [
        setBeforeLists,
        setUserDetails,
        userDetails
]);
1 Answers

When you refresh the app, the store will be reset. The token is gone. As we expected.

So, we can’t use the state to store the authentication token. This is where AsyncStorage comes onto the stage.

I'm replying to a react-native application. If it's a web application use session storage.

Let’s import AsyncStorage in the React Native project:

import { AsyncStorage } from "react-native";

Then, let’s create two functions,setToken and getToken, for storing and retrieving the persistent data. These are the main methods of this tutorial. Here, we are storing and retrieving the user data from/to AsyncStorage.

async storeToken(user) {
    try {
       await AsyncStorage.setItem("userDetails", JSON.stringify(user));
    } catch (error) {
      console.log("Something went wrong", error);
    }
  }
  async getToken(user) {
    try {
      let userDetails = await AsyncStorage.getItem("userDetails");
      let data = JSON.parse(userDetails);
      console.log(data);
    } catch (error) {
      console.log("Something went wrong", error);
    }
  }

componentDidMount() {
   this.getToken();
}

Let’s prove it. The token is thereafter you quit & reopen the app. Try it out yourself. Now, our app automatically logs you in after each session.

Hope this helps!

Related