Search code examples
javascriptreactjsauthenticationredux

Why user is logging out after refresh the page? React/Redux app


As in the title - the user is logging out when I reload the page in my React/Redux application. I store the token in localStorage but it doesn't work so there is probably any mistake. The token should be stored when the user logs in. Logging out works correctly. Here is my code:

auth.js (reducers directory - Redux):

import { LOGIN_SUCCESS, LOGIN_FAIL, LOGOUT_SUCCESS, REGISTER_SUCCESS, REGISTER_FAIL } from '../actions/types';

const initialState = {
  token: localStorage.getItem('token'),
  isAuthenticated: null,
  isLoading: false,
  isRegistered: false
}

export default function(state = initialState, action) {
  switch(action.type) {
    case REGISTER_SUCCESS:
      return {
        ...state,
        ...action.payload,
        token: null,
        isAuthenticated: false,
        isLoading: false,
        isRegistered: true
      }
    case LOGIN_SUCCESS:
      localStorage.setItem('token', action.payload.token);
      return {
        ...state,
        ...action.payload,
        isAuthenticated: true,
        isLoading: false,
      }
    case LOGIN_FAIL:
    case LOGOUT_SUCCESS:
    case REGISTER_FAIL:
      localStorage.removeItem('token');
      return {
        ...state,
        token: null,
        isAuthenticated: false,
        isLoading: false
      }
    default:
      return state;
  }
}

Response from the server when the user logs in: enter image description here


Solution

  • I don't really know how you check if there is a logged in user, but when you refresh the page, the store doesn't get automatically filled. So maybe you should add something like this if you check authentication state against isAuthenticated :

    const initialState = {
       token: localStorage.getItem('token'),
       isAuthenticated: localStorage.getItem('token') ? true : false, // or just !!localStorage.getItem('token')
       isLoading: false,
       isRegistered: false
    }
    

    or use some function to check localStorage and update the store accordingly.