1

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 ...?

1 Answer 1

3

In short, you have to maintain immutability. In your case, you have to make sure that:

  1. The elements array is copied.
  2. The updated element object is copied.
  3. The 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 };
}
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing. This is exactly what I looked for :) Thank you :) and thank you for advice ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.