M
M
Mesuti2020-04-14 01:00:30
JavaScript
Mesuti, 2020-04-14 01:00:30

How to write a function to change an object inside state?

Guys, tell me, please.
How to pass 2 parameters a key and a value to a function so that they change the corresponding keys?

state = {
        key: {
            id: 1,
            name: "John",
            surname: "Doe",
        }
    };

    const changeState = (name, value) => {
       this.setState({
            key[name] = value // не работает
        });
    }

   changeState("name", "NoJohn");

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Loli E1ON, 2020-04-14
@Mesuti

this.setState(state => ({
    ...state,
    key: {
        ...state.key,
        [name]: value
    }
}));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question