1

I'd like to know how to add an object in datasets, I'm trying to add an object in array with using setState, but It doesn't work at all .

my code is like this :

 const [DataContext, setDataContext] = useState([
    {
      labels: defaultLabels,
      datasets: [
        {
          label: "dataSetting",
          data: defaultDatas,
          backgroundColor: defaultBackgroundColor,
        },
      ],
    },
    {
      labels: defaultLabels,
      datasets: [
        {
          label: "dataSetting",
          data: defaultDatas,
          backgroundColor: defaultBackgroundColor,
        },
      ],
    }, 
    {
      labels: defaultLabels,
      datasets: [
        {
          label: "dataSetting",
          data: defaultDatas,
          backgroundColor: defaultBackgroundColor,
        },
      ],
    }, 

  const addAxis = index =>  {
    let addAxis = [...DataContext];
    addAxis[index].datasets.push({ label: "", data: "", background: "" });

    setDataContext(addAxis);
  };

1
  • 1
    that's because spread operator creates a shallow copy. you need to create a deep copy and then update the state Commented Aug 11, 2021 at 7:00

2 Answers 2

1

You need a deep copy to update the state:

const addAxis = index =>  {
  setDataContext(dataContext => dataContext.map((data, idx) => {
     return idx === index ? {
        ...data,
        datasets: [...data.datasets, { label: "", data: "", background: "" }]
     } : data
  })
};
Sign up to request clarification or add additional context in comments.

1 Comment

This is the most efficient way to do this, props to @DrewReese. You can use a library like lodash to clone deep.
1

You need to deep copy DataContext.

const _copy = (value) => {
    let object;
    if (Array.isArray(value)) {
        object = [];
        value.forEach((item, index) => {
            if (typeof value[index] === 'object') {
                object[index] = _copy(value[index]);
            } else {
                object[index] = value[index];
            }
        });
    } else {
        object = {};
        for (let key in value) {
            if (typeof value[key] === 'object') {
                object[key] = _copy(value[key]);
            } else {
                object[key] = value[key];
            }
        }
    }
    return object;
};

const addAxis = index =>  {
    let addAxis = _copy(DataContext);
    addAxis[index].datasets.push({ label: "", data: "", background: "" });

    setDataContext(addAxis);
 };

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.