jhamm
jhamm

Reputation: 25032

Why is my input not updating? - React

I can't figure out why my input is not updating. Here is my code:

state = {
    org: {
        orgName: ''
    }
};

updateInput = field => event => {
    this.setState({
        [field]: event.target.value
    })
}

render() {
    let { org } = this.state
    return (
        <input
            value={org.orgName}
            onChange={this.updateInput('orgName')}
        />
    )
}

I type data into the input. It calls updateInput and sets the state. When render is called, the org.orgNameis '' again. This should be working.

I have even added a log in the setState callback:

this.setState({
        [field]: event.target.value
}, () => console.log(this.state.org))

and it logs out the org info that has been entered into the input

What am I missing? How do I make this work?

Upvotes: 0

Views: 39

Answers (1)

Deryck
Deryck

Reputation: 7658

You have a nested object in your state - you are updating this.state.orgName instead of this.state.org.orgName

updateInput = field => event => {
    this.setState({
        [field]: event.target.value
    })
}

needs to be

updateInput = field => event => {
    this.setState({
        org: {
            ...this.state.org,
            [field]: event.target.value
        }
    })
}

Would recommend you avoid nesting objects in state though going forward. Will prove difficult to optimize later on.

Upvotes: 2

Related Questions