简体   繁体   中英

Using spread operator to add new value to key value pair in object

Struggling to figure out how to add a new item to an object from my reducer. This is the payload I am receiving GH

This is the relevant code in my reducer

const initialForm = { 
    nationality: '',
}
function addName(state= initialForm, action) {
    switch(action.type){
        case ADD_NEW_NATIONALITY:
            console.log('nationality',action.payload.name)
            return {
                ...state,
                [action.payload.nationality]: action.payload.value
            }
        default:
            return state
    }   
}

and my action creators

export const addFullName = newName => dispatch => {
    console.log(newName)
    axios.get(`https://api.nationalize.io?name=${newName.name}`)
        .then(res => {
            dispatch({ type: ADD_NEW_NATIONALITY, payload: res.data.country[0].country_id})
        })

Please help me figure this out

Your payload is just a plain value (not an object), so you cannot find action.payload.name and action.payload.value

And similarly, you cannot find action.payload.nationality either.

Here is how your action looks like

{ type: ADD_NEW_NATIONALITY, payload: 1} //`1` is country_id

To set nationality correctly, you can check the below implementation

const initialForm = { 
    nationality: '',
}
function addName(state= initialForm, action) {
    switch(action.type){
        case ADD_NEW_NATIONALITY:
            return {
                ...state,
                nationality: action.payload //update your `nationality` property with a plain value from `payload`
            }
        default:
            return state
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM