0

I have the following onClick event:

const handleClickOpen = (id) => {
        const newPieChartData=pieChartData.map((item)=>{
            if (item.id===id){
                const newItem={
                    ...item , open:true
                }
                console.log(newItem)
                return newItem
            } return item
        })
        
        setPieChartData(newPieChartData)
        console.log(pieChartData)
        addPieChartGroup(id)
    };

And this is how I declare the onClick event in a child component:

onClick={()=>handleClickOpen(id)}

Yet the state

[
        {
            id:uuidv4(),
            data:[],
            open:false,
        }
    ]

doesnt change at all , which is reflected in the console.log (This is logged for newItem {id: "4d95df0a-d463-4981-91ec-20ea323414e0", data: Array(0), open: true} and this is logged for the pieChartData:{id: "4d95df0a-d463-4981-91ec-20ea323414e0", data: Array(0), open: false}) . Why is that ? Thank you very much !

Peter Malik
  • 403
  • 4
  • 14
  • 1
    Setting state is asynchronous, so your console.log will show the old value. –  Jul 26 '21 at 11:48
  • As @ChrisG already told that setState is working asynchronously. What you can do is console log outside handleClickOpen function and then verify you state after click – Muhammad Bilal Bangash Jul 26 '21 at 11:51
  • @ChrisG I have also logged it outside the handler and I get the same result. Furthermore, I know that it didnt make any change because if open was being set to true , it would trigger the rendering of an additional component, which is not... So I guess there may be something else? – Peter Malik Jul 26 '21 at 11:52
  • @MuhammadBilalBangash Yep have done that, same result – Peter Malik Jul 26 '21 at 11:53
  • You need to post a [mre] so we can debug it then. –  Jul 26 '21 at 11:53
  • yes please share your code anywhere codesandbox etc – Muhammad Bilal Bangash Jul 26 '21 at 12:01
  • i think return is incorrect` if (item.id===id){ const newItem={ ...item , open:true } console.log(newItem) return newItem } else return item` – zahra zamani Jul 26 '21 at 12:04
  • @zahrazamani I don't think so , because if the, `if` branch was entered the second return, would turn obsolete – Peter Malik Jul 26 '21 at 12:17

0 Answers0