I have a question. How can I update my value in my nested object ?
so my Redux state looks like:
const initialState = {
elements: [],
selectedElement: {},
};
In elements array I will storage my "elements" with structure like this:
{
id: 3243,
elemType: 'p',
content: 'some example content',
style: {
fontSize: 30,
color: "red",
textDecoration: "underline",
fontFamily: "Arial"
}
}
And now I'd like change values in style. Maybe fontSize, maybe color... depends which property will be selected.
I've made action creator which give me id, property, value for these changes.. but the problem is that I don't know how to exactly write code in reducer :(
Action Creator
export const updateElement = (property, value, id) => {
return {
type: 'UPDATE_ELEMENT',
property,
value,
id
}
}
Reducer
const {id, elemType, content, style, type, selected, property, value} = action;
case 'UPDATE_ELEMENT':
const elementForUpdate = state.elements.find(element => element.id === id);
console.log(id, property, value);
return ...?
In short, you have to maintain immutability. In your case, you have to make sure that:
elements
array is copied.style
object of the updated element is copied.You can accomplish all of these with a single map
:
case 'UPDATE_ELEMENT': {
const elements = state.elements.map(el => {
if (el.id === id) {
const style = { ...el.style, [property]: value };
return { ...el, style };
} else {
return el;
}
});
return { ...state, elements };
}