Redux: How can i update only name in category object in reducer

Created on 25 Jun 2016  Â·  8Comments  Â·  Source: reduxjs/redux

I have a object below:

categoryDetail: {
        isFetching: false,
        category: {
            id: '',
            name: '',
            publish: '',
            time_create: '',
            attributes: []
        }
    }

How can i update only name in category object in reducer.
I'm trying use return {...state, category: {name: cateName}}; and I get result:

categoryDetail: {
        isFetching: false,
        category: {
            name: ''
        }
    }

Please tell me how to update only name in category object and keeping all fields.
Thanks so much.

Most helpful comment

Awesome, glad to hear! Sorry for the typo again!

All 8 comments

This will fix the issue:

return {
  ...state,
  category: {
    ...state.category,
    name: cateName
  }
}

I think this might be a case for using reducer composition and having a separate categoryReducer, see this and the following lessons of Dan's redux course for information on what that means and how to do it!

Thanks so much @mxstbr for help :)

Hi @mxstbr ,
I set it but i get error :

Uncaught ReferenceError: category is not defined

Ah sorry, I had a typo, my bad! :blush: should be:

return {
  ...state,
  category: {
    ...state.category,
    name: cateName
  }
}

Fixed above!

yeah, it work!!!. Thanks @mxstbr. Have a nice day. :)

Awesome, glad to hear! Sorry for the typo again!

@chienvuhoang Could be a great time to look into lenses if you often have to write code with deeply nested object spreads. See ramda's lensPath and set.

with lenses you could write something like

const catNameLens = lensProp(['category', 'name'])
return set(catNameLens, cateName, state)

Thanks @Koleok

Was this page helpful?
0 / 5 - 0 ratings

Related issues

olalonde picture olalonde  Â·  3Comments

ilearnio picture ilearnio  Â·  3Comments

caojinli picture caojinli  Â·  3Comments

benoneal picture benoneal  Â·  3Comments

cloudfroster picture cloudfroster  Â·  3Comments