Search code examples
javascriptreact-nativeredux-toolkit

How to get token from localstore to redux store when i refresh the app or restart the app in react native


I am trying to store the token in local store and try to get token value when the user open app but i get undefined while getting the app in redux-toolkit anyone please help me with this

import {createSlice, PayloadAction} from '@reduxjs/toolkit';
import {User, LoginPayload, LoginPayloadError} from './interface';
import {login} from '../../service/authService';
import AsyncStorage from '@react-native-async-storage/async-storage';

let savedToken;

const getData = async () => {
  savedToken = await AsyncStorage.getItem('token');
};

getData();

console.log(savedToken);

const initialState: User = {
  token: savedToken ? savedToken : '',
  id: 0,
  email: '',
  nicename: '',
  firstName: '',
  lastName: '',
  displayName: '',
  role: '',
  loading: false,
  error: '',
};

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder.addCase(login.pending, (state, action) => {
      state.loading = true;
    }),
      builder.addCase(login.fulfilled, (state, action) => {
        const saveToken = async () => {
          await AsyncStorage.setItem('token', action.payload.token);
        };
        saveToken();
        return {
          ...state,
          loading: false,
          ...action.payload,
        };
      }),
      builder.addCase(login.rejected, (state, action) => {
        return {
          ...state,
          loading: false,
          error: action.payload,
        };
      });
  },
});

export default userSlice.reducer;

I have to define SavedToken for storing the token and try to get the value from the getData function. if the console.log(inside the getData then i will get the token value but if the console out the function i will get undefined


Solution

  • Maybe you should do it differently. I don’t know your project structure but I think you could do something like that in your App.js

    // get and save token before anything
    useEffect(() => {
      const getData = async () => {
        const token = await AsyncStorage.getItem('token');
    
         // save the token to the redux store
         setUser({token});
    
      };
    
      getData();
    }, []);
    

    You can read this interesting link Authentication flow and Implement the logic for restoring the token