D
D
DanceMonkeyTime2020-10-13 10:28:15
JavaScript
DanceMonkeyTime, 2020-10-13 10:28:15

How do I update the value of an object?

Hello. I have such an array in the state:

[{
    "companyName": {
        "key": "companyName",
        "value": ""
    },
    "country": {
        "key": "country",
        "options": [],
        "value": ""
    },
    "region": {
        "key": "region",
        "options": [],
        "value": ""
    },
    "companyWebsite": {
        "key": "companyWebsite",
        "value": ""
    }
}]


I have an input text, onChange of which the value in this array should change. There can be many objects, so indexing is needed here.

https://codesandbox.io/s/funny-euclid-hyhi5?fontsi...

Can you tell me what I'm doing wrong??

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MagnusDidNotBetray, 2020-10-13
@MagnusDidNotBetray

I don’t know React at all, but I see that you are constantly pushing a new object into the array, instead of changing the current one. Maybe that's what you wanted to do?

const handleChange = (index, value, key) => {
    const newFields = [...fields];
    newFields[index][key].value = value;
    setFields(newFields);
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question