Hai Tien
Hai Tien

Reputation: 3117

Redux store render multiples state. Is it normal?

I received state nested in state and it has many states rendered.

You see from my photo below.

enter image description here

enter image description here

Here is my LoginReducer

import {
    LOGIN_SUCCESS,
    LOGIN_FAIL,
    USER_LOADED,
    AUTH_ERROR
} from '../actions/typeName';

const initialState = {
    token: localStorage.getItem('token'),
    isAuthenticated: null,
    loading: true,
    user: null
}
const loginReducer = (state = initialState, action) => {
    const {
        type,
        payload
    } = action;

    switch (type) {
        case USER_LOADED:
            return {
                ...state,
                isAuthenticated: true,
                    loading: true,
                    user: payload
            };
        case LOGIN_SUCCESS:
            localStorage.setItem('token', payload.token)
            return {
                ...state,
                isAuthenticated: true,
                    loading: false
            }
            case AUTH_ERROR:
            case LOGIN_FAIL:
                localStorage.removeItem('token')
                return {
                    ...state,
                    token: null,
                        isAuthenticated: false,
                        loading: true
                }
                default:
                    return {
                        state
                    }
    }
}

export default loginReducer;

And here is myaction.

export const LoginAction = (email, password) => async dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json'
    }
  }
  const body = JSON.stringify({email, password});
  try {
    const res = await axios.post('/api/admin/login', body, config);
    dispatch({
      type: LOGIN_SUCCESS,
      payload: res.data
    });
    dispatch(loadUser());

  }catch(err){
    const errors = err.response.data.errors;

    dispatch({
      type: LOGIN_FAIL,      
    });

    if(errors) {
      errors.forEach(error => {
        dispatch(NotificationAction(error.msg, 'error'));
      })
    }

  }
}

If it is not normal and how to prevent this? Thank you so much.

Upvotes: 0

Views: 55

Answers (2)

Harald Gliebe
Harald Gliebe

Reputation: 7564

The default case is not handled correctly in your reducer. Use

switch (type) {
  ...
  default:
    return state;
}

instead. If you return { state } the current state will be wrapped in a new object with an attribute state, that's what you see in the inspector.

Upvotes: 2

John_ny
John_ny

Reputation: 807

Its not normal, usually we will get state and the reducers defined in it. In your case state with the following reducers

  • loginReducer

  • notificationReducer

  • listUsersReducer and so on.

    Can u please provide the respective action file. I think the way u are passing inside the switch() should be action.type instead of type itself.

Upvotes: 1

Related Questions