user4747724
user4747724

Reputation:

react this.setState isn't updated state

I'm trying to figure out why a call to this.setState isn't updating state.

I have the following lines method:

changeState(state, value){
        this.setState({state:value}, ()=>console.log(this.state));
    }

There are a few function using this, but one is a file upload component. Its a simple component that either renders a file input OR it renders an iframe, disabled input, and button. When the button is clicked I want to change the state in the parent component which then rerenders the file component and shows a file picker.

The call to this.setState seems to work ok, but when I console log state after it runs or if I stop execution before the next render takes place state is unaffected. My file upload component has a method like this:

renderField(field){
        if(this.props.hasOwnProperty('file') && this.props.file){
            return(
                <div>
                    <iframe src={this.props.file} frameborder="0"> </iframe>
                    <input
                        disabled
                        placeholder={this.props.file}
                        name={field.name}
                        type='text'
                    />
                    <span onClick={()=>this.props.changeFile(this.props.file_type, null)}>&times; Remove</span>
                </div>
            )
        }else{
            return(
                <input
                    {...field}
                    type={field.type}
                    name={field.name}
                    onChange={(event) =>{
                        field.input.onChange(field.input.value = event.target.files[0])}
                    }
                />
            )
        }
    }

when I call the method I get this output: enter image description here

however after console logging my state is anything but changed: enter image description here

Upvotes: 2

Views: 81

Answers (1)

Tholle
Tholle

Reputation: 112777

You don't want to set the state property in your state, but the property name that state contains.

You can use a computed property name for this.

changeState(state, value) {
  this.setState({ [state]: value }, () => console.log(this.state));
}

Upvotes: 5

Related Questions