Search code examples
reactjsapiobjectnesteddestructuring

Destructuring the nested objects fetched from an API call using "curly braces method"


I fetched the data like this:

  constructor(){
    super();    
    this.state = {
      fetchedData : [] 
    }
  }
  componentDidMount(){
    fetch("https://api.randomuser.me")
          .then(response => response.json())
          .then(data => {            
            this.setState({
                  fetchedData : data.results[0]
                          })
                              });                                                                                                                                     
  }

Got this result with this.state.fetchedData:

Complete Data fetched

Then tried the following code to destructure the result:

render(){    
let {name} = this.state.fetchedData;

It works fine and I got the following result with console.log(name):

Results with the First Level of destructuring

So I wanted to further move down the nested object, but when I tried the following code:

render(){    
    let {name:{first, last, title}} = this.state.fetchedData;

It gave me the following error:

Error message after deeper de-structuring


Solution

  • You have a mismatch of types here. You are initialising fetchedData with empty array, and then expect it to have properties first, last and tilte.

    You should initialise with a valid entry instead of empty array:

    constructor(){
        super();    
        this.state = {
          fetchedData : {name: {first: '', last: '', title: ''}}
        }
      }
    

    Furthermore, this is needed because of the async request. The corresponding then handler (this.setState({fetchedData:...})) is invoked later. Therefore, your component will be rendered before the setState call with its initial values.