Search code examples
javascriptreactjsreact-hooksjavascript-objectsuse-state

Adding items in the nested array of React state


I'm trying to add new items to an array of an object that resides in another object of a state. Pretty nested.

So I tried the following way...

// The initial data
[options, setOptions] = useState({
    name: 'Name goes here'
    type: 'type goes here'
    series : [{
        type: 'series type',
        label: 'series label'

})

Now I want to add another object inside the object of series array with useEffect(). And I tried:

useEffect(() => {
    // other functionalities goes here
    setOptions({
        ...options, // for copying previous data outside of series
        series: [{
            ...options.series, //this is for copying previous data of series
            tooltip: {
                enable: true,
        }]
    })
}, [refreshData])

The way I'm copying ...options works absolutely fine, But when I try to copy ...options.series it adds a new copied object inside the object of series array like the following:

{
    name: 'Name goes here' //fine
    type: 'type goes here' //fine
    series: [{
        {type: 'series type', label: 'series label'}, //not fine
        tooltip: {enable: true} //not fine
        //what I want is: to have previous object data and tooltip appended as another item
    }]
}

The way I want the object to be is:

{
    name: 'Name goes here' //fine
    type: 'type goes here' //fine
    series: [{
        type: 'series type', 
        label: 'series label'
        tooltip: {enable: true}
    }]
}

Can Anybody help me regarding this. I would appreciate any help.. Thanks


Solution

  • here is sample of what you are trying to achieve .

    const d = {
        name: 'Name goes here',
        type: 'type goes here',
        series : [{
            type: 'series type',
            label: 'series label'
      }]
    }
    
    
    const newD = {
        ...d,
        series: [
            {
              ...d.series[0], // problem is here
              tooltip: {
                enable: true,
              }
            }
          ]
      } 
    console.log (newD)