1

I'm trying to implement authentication in a project with redux and next js.

I have a userSlice where I have user info and token in initial state. I'm checking the localstorage for the token. but I'm getting an error:

ReferenceError: localStorage is not defined

How can I add user's token from localstorage in initial state?

const userTokenFromStorage = localStorage.getItem('userToken')
  ? localStorage.getItem('userToken')
  : null;

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    user: { info: null, token: userTokenFromStorage },
  },
  reducers: {
    login: (state, action) => {
      state.user.token = action.payload;
    },
    getDetails: (state) => {
      getUserDetails(state.user.token).then((details) => {
        state.user.info = details;
      });
    },
  },
});
Xaarth
  • 1,021
  • 3
  • 12
  • 34

0 Answers0