Search code examples
javascriptarraysreactjsreact-hookssetstate

setState not updating the array in react


I am working on a react app where I have to change keys of objects in an array.Here's my code:

getInterfaces(){
    //assign a array to interfaceOption state
    let interfaceOptions=[
      {
        "interface_name": "ORU",
        "interface_id": "1"
      },
      {
        "interface_name": "MLM",
        "interface_id": "2"
      },
    ]
   
    //change interfaceOptions keys to title and value
    let interfaceOptionsWithTitle = interfaceOptions.map(function(item){
      return {
        title: item.interface_name,
        value: item.interface_id
      }
    })
    console.log(interfaceOptionsWithTitle)
    this.setState({
      interfaceOptions: interfaceOptionsWithTitle
    })
  
    //print updated interfaceOptions
    console.log(this.state.interfaceOptions)

  }

Here I initially assign a array,then I change its keys and print it using console.log and it prints the updated array but when I then setState the array and console log it again,it returns a empty array.Can someone help me to understand this?

Will this work if I want to update interfaceOptions?

this.state.interfaceOptions = this.state.interfaceOptions.map(item => {
      return {
        title: item.interface_name,
        value: item.interface_id
      };
    });

Thanks


Solution

  • Becasue state only has new value when component re-render. So just put console.log to outside function getInterfaces to see the new value

    getInterfaces(){
    ...
    }
    console.log(this.state.interfaceOptions)