skip to Main Content

Im trying to reassign the value of scscf before sending it to container but its always undefined

Here are my code flow

constructor(){
        this.state = {scscf: null}

Data init on componentWillReceiveProps

componentWillReceiveProps(nextProps) {
    this.setState({scscf: nextProps.currentItem.scscf})
}

My onchange handle

    onChangeSCSCF(atrr, event){
        if (atrr == FIELDS.SCSCF) {
            this.setState({scscf: event.target.value});
        }

I have a data object here and want to reassign it with the value of this.state.scscf to use

onSubmit(e) {
        data = {scscf: this.state.scscf}
}

My render code

<TextField 
name="scscf"  
className="input-text" 
type="text" 
onChange={this.onChangeSCSCF.bind(this, FIELDS.SCSCF)} 
value={this.state.scscf}/>

My debug on the console: Nevertheless, ‘React Developer Tools’ shows that indeed these states have values but I cant assign it to my data object

enter image description here

I dont know why I can reassign the state to my data object and sending it to container.
How can I fix it?

2

Answers


  1. Try this

    constructor(){
        this.state = {scscf: null}
        this.onChangeSCSCF = this.onChangeSCSCF.bind(this);
    
    ...
    
    <TextField 
     name="scscf"  
     className="input-text" 
     type="text" 
     onChange={(e) => this.onChangeSCSCF(FIELDS.SCSCF, e)} 
     value={this.state.scscf}/>
    

    or

    onChangeSCSCF = (attr) => (event) => {
        if (attr == FIELDS.SCSCF) {
            this.setState({ scscf: event.target.value });
        }
    }
    
    ...
    
     <TextField 
     name="scscf"  
     className="input-text" 
     type="text" 
     onChange={this.onChangeSCSCF(FIELDS.SCSCF)} 
     value={this.state.scscf}/>
    
    Login or Signup to reply.
  2. This issue is related to asynchronous nature of setState. For resolving this issue you can use Second argument of setState function, that will be executed once the state has been updated. Try this code:-

    onChangeSCSCF(atrr, event) {
        if (atrr === FIELDS.SCSCF) {
            this.setState({ scscf: event.target.value }, () => {
                console.log('Updated state:', this.state.scscf);
            });
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search