O
O
Oleg Gamega2016-10-08 12:53:18
JavaScript
Oleg Gamega, 2016-10-08 12:53:18

How to refer to nested object?

Hello.
I am writing a react redux application, I want to use something like this state

const initialState = {
    user: {
        response: {},
        error: null,
        isFetching: false
    },
    friends: {
        response: {
            count: 0,
            items: []
        },
        error: null,
        isFetching: false
    }
};

but swears when I turn to response like this
switch (action.type) {
        case types.GET_USER_LOADED:
            return {...state, user.response: action.payload};
.......

ps
originally did without nested objects
const initialState = {
    user: {},
    userIsFetching: false,
    userError: null,
    
    friends:{
        count:0,
        items:[]
    },
    friendsIsFetching: false,
    friendsError: null
};

const  api = (state = initialState, action)=>{
    switch (action.type){
        case types.GET_USER_LOADED:
            return{...state, user:action.payload};
........

but the project grows, and it becomes not very convenient

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2016-10-08
@gadfi

You need to sequentially recreate all nested objects:

return { 
  ...state,
  user: {
    ...state.user,
    response: { ...action.payload },
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question