1

I have an array of Objects in my props from my API but I need to modify the elements in this array of Objects and then pass it to a player on my application. I can successfully get my array of object but when I try to modify the elements and set the data into a state, The new state ends up having just the last item of my list. Here is my code,

        if(musicitem.musics){
            if(musicitem.musics.length === 0){
                this.setState({musicLimited:true })
            }
            else{
                return musicitem.musics.map((item, index)=>{
                    this.setState({
                        musics:[
                            ...musics,
                            {
                                url:apiConstants.API_MUSIC_FILES+item.url,
                                cover:apiConstants.API_MUSIC_FILES+item.cover,
                                artist:item.artist,

                            }
                        ]
                    })
                });
            }
        }

I expect my state of musics to have an array of newly constructed objects but that is not the case. It ends up with just the last object that is expected to be in my array of objects. This means that, it has actually loop through the array of objects from props but the next State keeps overriding the previous state.

1 Answer 1

2

You should mention previous state's property(i.e. music) to get setState know that while using spread operator.

You can access previous state as passing first params to this.setState().

Example : this.setState(prevState => ({ music : [...prevState.music, {artist:item.artist}] }))

Your code should be updated like this :

 if(musicitem.musics){
        if(musicitem.musics.length === 0){
            this.setState({musicLimited:true })
        }
        else{
            return musicitem.musics.map((item, index)=>{
                this.setState(prevState => ({
                    musics:[
                        ...prevState.musics, // use prevState
                        {
                            url:apiConstants.API_MUSIC_FILES+item.url,
                            cover:apiConstants.API_MUSIC_FILES+item.cover,
                            artist:item.artist,

                        }
                    ]
                }))
            });
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much. It works like magic. 1) i thought the ...musics, will do that besides that, I tried passing the currentState and prevState and I didnt get it working. definitely because I did not add the .musics to it
Glad to provide assist ! Yes inside setState's prop key-value pair, you have to explicitly define previous state's property using it's object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.