I'm learning Redux and having trouble trying to figure out how to add a key pair to a dictionary:
//Page Dictionary
{
randomId1: { aPageObj },
randomId2: { aPageObj }, etc
}
I tried this but that doesn't work
//action
export function addPage( pageId, pageObj ) {
return { type: types.ADD_PAGE, pageId, pageObj };
}
//reducer
case types.ADD_PAGE: {
return Object.assign({}, state, {
pages: {
...state.pages, action.pageId: action.pageObj
}
});
}
What am I doing wrong? Still trying to figure out how to not mutate the state..
You need to use computed property name of object literal (with []
):
pages: {
...state.pages, [action.pageId]: action.pageObj
}
Furthermore if you can use object spreas syntax, you can omit Object.assign
, for example:
return {
...state,
pages: {
...state.pages, [action.pageId]: action.pageObj
}
}