Search code examples
arraysreactjssetstate

Unable to setState with array of objects


I'm trying to setState of an empty array with an array of objects on component load.

I've tried new ES6 syntax, I've tried mapping, join, etc but can't get it to work.

The console output of the array I'm trying to insert (not push) into my state looks correct.

mapped arrayObj : [{"word":"teacher","correct":true,"image":"/Assets/Art/Icons/teacher.png"},{"word":"backpack","correct":false,"image":"/Assets/Art/Icons/backpack.png"},{"word":"paper","correct":false,"image":"/Assets/Art/Icons/paper.jpg"}]

Here's the function where I'm mapping my array of objects and then I'm trying to setState of my empty answersObj.

mapArray(){

    const arrayObj = this.state.data.answers.map(obj => obj);
    let shuffledObjArray = [{}];

    shuffledObjArray = this.shuffleArray(arrayObj)



    this.setState({
        answersObj: shuffledObjArray
    })

    return shuffledObjArray;
}

I call the mapArray function when the component loads

componentDidMount() {
    this.mapArray();
}

Solution

  • Don't forget that setState is async function, so the state doesn't sets immediately.

    For example this piece of code works for me:

        async componentDidMount() {
    
         await this.mapArray();
    
        console.log(this.state)
    
    }
    

    the obj state gets the value it needs, while w/o the async/await it would print empty state.

    Therefore, if you need to render the data from that state I'd suggest making 'dataLoaded' bool and render the data only if the data finished loading.

    enter image description here