cham
cham

Reputation: 10712

TypeError: "x" is (not) "y" after destructuring an object

In my react app, when I run this code I get TypeError: "x" is (not) "y":

deletePersonHandler = (personIndex) => {
    const { persons } = this.state.persons;
    persons.splice(personIndex, 1);
    this.setState({ persons });
}

There is no problem when I do not use destructuring:

deletePersonHandler = (personIndex) => {
    const persons = this.state.persons;
    persons.splice(personIndex, 1);
    this.setState({ persons });
}

If it helps this method is passed into a functional component as a click property:

        persons = (
            <div>
                {this.state.persons.map((person, index) => {
                    return <Person name={person.person} age={person.age} click={() => this.deletePersonHandler(index)} changed={this.nameChangedHandler.bind(this)} />;
                })}
            </div>
        );

Why does destructuring make a difference?

Upvotes: 1

Views: 54

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

You're trying to destructure this.state.persons as an object with a property of persons - but you want the persons property of this.state, not the persons property of this.state.persons (which doesn't exist). Instead, do:

const { persons } = this.state;

Upvotes: 4

Related Questions