reactjs - Redux nested objects as state - is this possible/optimal -
i'm new redux please bear me. wondering if following possible and/or optimal , if so, how update nested object values in reducer?
const initialstate = { banner: { backgroundcolor: 'black', text: 'some title', textcolor: 'white', image: null }, nav: { mainopen: false, authopen: false, } ... }
and in reducer not seem work...
export default function reducer(state = initialstate, action = {}) { const {type, data} = action; switch (type) { case set_banner_text: return { ...state, banner.text: data //<-- ****this fails unexpected token!!!**** } ... }
or better to have 'banner' reducer, 'nav' reducer , on??
tia!
since you're updating key of object, try using update key
const state = { ...initialstate, banner: { ...initialstate.banner, // extend text: 'newtext' } }
which translates to
var state = _extends({}, initialstate, { banner: _extends({}, initialstate.banner, { text: 'newtext' }) });
in es5
check jsbin
edit: stated in comment below, overwrite whole banner object if code used above. can try other answer in thread using object.assign()
, clone banner
object. if still want use spread operators, updated answer.
i think better have specific reducers nested state.and write this
export function rootreducer(state = initialstate, action) { switch (action.type) { case set_banner_text: case set_banner_bg: return object.assign({}, state, { banner: bannerreducer(state.banner, action) } ); // ... default: return state; } } function bannerreducer(state, action) { switch (action.type) { case set_banner_text: return object.assign({}, state, {text: action.payload}); case set_banner_bg: return object.assign({}, state, {backgroundcolor: action.payload}); // ... default: return state; } }
Comments
Post a Comment