Pervious state is removed when I update state in react native redux

Viewed 42

I call get_user_profile_api inside the app after login. On successful login my app has user and token in the state. But as soon as GET_USER_PROFILE_SUCCESS is called, the state is left only with userData and isLoading. user and token are removed from the state.

import { CONST } from '../../utils/Const';
import * as types from './types';

const initialState = {
  isLoading: false,
  user: null,
  userData: null,
  isLoggedIn: false,
  token: '',
};

export default authReducer = (state = initialState, action) => {
  console.log('action :: ', action);
  switch (action.type) {
    case types.GET_USER_PROFILE_LOADING:
    case types.LOGIN_LOADING:
      return {
        isLoading: true,
      };

    case types.GET_USER_PROFILE_SUCCESS:
      return {
        ...state,
        isLoading: false,
        userData: action.payload,
      };

    case types.LOGIN_SUCCESS:
      return {
        ...state,
        isLoading: false,
        isLoggedIn: true,
        user: action.payload.user,
        token: action.payload.token,
      };

    case types.LOGIN_ERROR:
    case types.GET_USER_PROFILE_ERROR:
      return {
        ...state,
        isLoading: false,
      };

    default:
      return {
        ...state,
        isLoading: false,
      };
  }
};
2 Answers

there is nothing wrong with this code I think the issue is where you are calling these actions from and you can call them inside a use-effect hook to get a user profile if there is a token or maybe you are not mapping state to props correctly

I was not writing ...state in the LOADING case. That's why my state was being removed.

Related