Avetik Harutyunyan
Avetik Harutyunyan

Reputation: 21

Redux store double nesting

Im getting double nested state after api call. Here is it.

Screenshot from redux devtools

Here are my actions

export const getUserSuccess = user => ({
  type: GET_USER_SUCCESS,
  user,
});

export const getUserFailure = error => ({
  type: GET_USER_FAILURE,
  error,
});

export const getUserRequest = () => (
  dispatch => (
    axios.get('./user.json')
      .then(response => dispatch(getUserSuccess(response.data)))
      .catch(error => dispatch(getUserFailure(error)))
  )
);

here is my user reducer

export default function user(state = {}, action) {
  switch (action.type) {
    case GET_USER_SUCCESS:
      return {
        ...state,
        user: action.user,
      };
    case GET_USER_FAILURE:
      return {
        ...state,
        error: action.error,
      };
    default:
      return state;
  }
}

and here is my root reducer

export default combineReducers({
  user,
});

Upvotes: 2

Views: 513

Answers (3)

Sean Kwon
Sean Kwon

Reputation: 907

Judging by this quote

If I'll try that with array of users then array will be destroyed

Why not use Object.assign()?

return Object.assign({}, state, {user: [...state.user, ...action.user]})

Assuming that having multiple users is a possibility, why not just maintain the user property in your state as an array?

Upvotes: 0

dhorelik
dhorelik

Reputation: 1507

You need to spread the data which comes for user, no need to assign it to user. Your reducer is in it already

case GET_USER_SUCCESS:
  return {
    ...state,
    ...action.user
  };

Upvotes: 2

cchamberlain
cchamberlain

Reputation: 17956

If this reducer should update the state with the complete representation of the new user (and discard old data) you should just return the new user as state.

Can you give the following a shot?

export default function user(state = {}, action) {
  switch (action.type) {
    case GET_USER_SUCCESS:
      return action.user;
    case GET_USER_FAILURE:
      return {
        ...state,
        error: action.error,
      };
    default:
      return state;
  }
}

Upvotes: 0

Related Questions