ykn121
ykn121

Reputation: 855

What is the best practice to save access token in react-native app with redux?

What is the best practice to save access token in react-native app with redux?

In Redux, I used to save the whole credential, including some user information to the state:

//Actions
export const successfulLogin = (firebaseAuth) => ({
    type: 'LOGIN_SUCCESSFUL',
    firebaseAuth
});

//Reducer
const authentication = (state = {}, action) => {
    switch (action.type) {
        case 'LOGIN_SUCCESSFUL':
            return {
                ...state,
                firebaseAuth: action.firebaseAuth
            };
        default:
            return state;
    }
}
export default authentication

After that, I found a new module redux-persist, which helps me to save the state to device storage, localStorage. However, everything in the store will be saved. Is it a good practice to save access token with redux-persist?

If not, what should I use?

Upvotes: 3

Views: 1615

Answers (2)

Pawel
Pawel

Reputation: 31620

It's been a while since this question was asked but with redux-persist you don't need to save the entire store. You can provide keys that you want to store and it will ignore keys that you have not specified.

Upvotes: 0

timotgl
timotgl

Reputation: 2925

I think what you're describing works, but it's a bit overkill to save the entire store if you only need one access token. Therefore I'd say it's best practice to accomplish exactly what you need with a bit of code.

As an alternative to using redux-persist you can just do this side effect handling yourself:

  1. Read the access token from localStorage when redux' createStore is called and pass it into the preloaded state. Or..
  2. Dispatch an action like SET_ACCESS_TOKEN to add the token to the redux store at a later point.
  3. To save the token right after successful login, you can trigger a side effect (calling a module that is responsible for writing something to localStorage) in the respective async action creator.

That's it, no additional modules necessary.

Upvotes: 2

Related Questions