N
N
nivaech2019-12-18 01:29:28
JavaScript
nivaech, 2019-12-18 01:29:28

How to add a parameter to an object?

There is an object with data about the subject.

const { title, description, price, category, sizes, color, id } = singleItem;

Before purchasing an item, the user must select the size and color. When you click on the size and color, they are entered in the state.
const [chosenParameters, setParameters] = useState({ size: '', color: ''});

    const pickSize = (size) => {
        setParameters(
            { ...chosenParameters, size: size }
        );
    };
        
    const pickColor = (color) => {
        setParameters(
            { ...chosenParameters, color: color }
        );
    }

How can I modify the function so that a new parameter is added to the singleItem object, pickedProps, with the values ​​size and color? Or instead of one object - two additional parameters of the same name.
My solution looks like this, but it doesn't work.
const pickSize = (size) => {
        setParameters(
            { ...chosenParameters, size: size }
        );
        return {
            ...singleItem, pickedSize: size
        }
    };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolay Matyushkin, 2019-12-18
@nivaech

for example like this:

const { title, description, price, category, sizes, color, id } = singleItem;

    const [chosenParameters, setParameters] = useState({ ...singleItem, size: '', color: ''});

    const pickSize = (size) => {
        setParameters({...chosenParameters, size: size});
    };

    const pickColor = (color) => {
        setParameters({...chosenParameters, color: color});
    };

It turns out that we make a copy of the singleItem object from the chosenParameters parameter with additional size and color parameters. The pickSize function will return this copy with the size parameter set, and the pickColor function, respectively, color.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question