0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.