简体   繁体   中英

how to update nested useState?

Hey there im having an issue on updating the useState. I saw some example but when trying to implement it it does not work.. Anyone can give me a hand on sorting this little issue?

this is the original state and i need to update labels

        setChartData({
            labels: [ ],
            datasets:[
            {
                label:'Sales',
                data:[ //values for population num
                    
                ],
                backgroundColor:[
                    'rgba(255, 99, 132, 0.6)',
                    'rgba(54, 162, 235, 0.6)',
                    'rgba(255, 206, 86, 0.6)',
                    'rgba(75, 192, 192, 0.6)',
                    'rgba(153, 102, 255, 0.6)',
                    'rgba(255, 159, 64, 0.6)',
                    'rgba(255, 99, 132, 0.6)'
                ]
            }
            ]
        })

this is the array im trying to assign to labels array

        for (let y = 0; y < weeks.length; y++) {
            setChartData(prevState => ({
                ...prevState,
                labels: {
                    ...prevState.labels,
                    weeks[y]
                }
            }))
        }

Oops: You've used the wrong braces in your loop! Try this:

for (let y = 0; y < weeks.length; y++) {
  setChartData((prevState) => ({
    ...prevState,
    labels: /* { */ [
      ...prevState.labels,
      weeks[y]
    ] /* } */
  }));
}

You were replacing your labels array with an object using an invalid syntax, this is probably what you meant to do.

Try without taking the prevState as an argument in the callback, like this:

for (let y = 0; y < weeks.length; y++) {
            setChartData(() => ({
                ...chartData //or whatever you called your state variable.
                labels: {
                    ...chartData.labels,
                    weeks[y]
                }
            }))
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM