Somi
Somi

Reputation: 141

Delete objects in Array in sequence but first one

I'm trying to remove objects in the array from the end in sequence So I tried to use pop and splice but for some reason, when I use the pop function then all the objects are removed, and got an error : is not a function and when I use the splice function then all the objects are removed here is my code :

const [appendChartData, setAppendChartData] = useState(chartData.datasets);
const appendAxis = e => {
    e.preventDefault();
  
    setAppendChartData([...appendChartData, AppendData]);
  };
    const deleteAxis = () => {
      setAppendChartData(appendChartData.splice(-1, 1));
     /// setAppendChartData(appendChartData.pop());
  };

chartData.datasets

export let chartData =[  {
    labels: defaultLabels,
    datasets: [
      {
        label: "dataSetting",
        data: defaultDatas,
        backgroundColor: defaultBackgroundColor,
      },]

AppendData

export let AppendData = {
  label: "dataSetting",
  data: defaultDatas,
  backgroundColor: defaultBackgroundColor,
};

so I'd like to remove the array in sequence from the end

Upvotes: 0

Views: 40

Answers (1)

Mihai Matei
Mihai Matei

Reputation: 24276

The way you used the state is wrong. You should use the chartData as state:

const [appendChartData, setAppendChartData] = useState(chartData);

const appendAxis = e => {
    e.preventDefault();
  
    setAppendChartData({
        ...appendChartData,
        datasets: [
           ...appendChartData.datasets,
           AppendData
        ]
    });
};

const deleteAxis = () => {
    setAppendChartData({
        ...appendChartData,
        datasets: appendChartData.datasets.splice(-1, 1)
    });
};

Also, be careful about your chartData since I saw that you defined it as an array of objects. If that's true then you must consider it in the code above.

Upvotes: 1

Related Questions