I am trying to store the token in local storage (react-native-async-storage). I have done setting up the create slice and need to store the token, since storing and retrieving is an async process where to keep the logic, I know we cannot keep the async logic inside the createslice.
authSlice.js
import {createSlice} from '@reduxjs/toolkit';
import AsyncStorage from '@react-native-async-storage/async-storage';
const initialState = {
isLoggedIn: false,
token: null,
};
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
login: (state, action) => {
state.isLoggedIn = true;
},
logout: (state, action) => {
state.isLoggedIn = false;
},
},
});
export const {login, logout} = authSlice.actions;
export default authSlice.reducer;
I have the same code/logic for web app and it works fine but cant achieve the same in react native because of async behavior
import { createSlice } from "@reduxjs/toolkit";
const token = JSON.parse(localStorage.getItem("token")) || null;
const initialState = {
token,
isLoggedIn: !!token,
};
const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
login: (state, action) => {
state.token = action.payload.token;
localStorage.setItem("token", JSON.stringify(action.payload.token));
state.isLoggedIn = true;
},
logout: (state, action) => {
state.token = null;
localStorage.removeItem("token");
state.isLoggedIn = false;
},
},
});
export const { login, logout } = authSlice.actions;
export default authSlice.reducer;
How to achieve the same in react native ?