I am using an external library to build a Taskboard and what I want to achieve is to add a new column when clicking and add column button. I am struggling with adding the column, I have the newly created column but it doesn't get added to the array. What am I doing wrong and how can I insert the newly created column? Here is my code:
onAddColumn = () => {
const newColumn: TaskBoardColumnModel = {
id: this.state.columnsData.length 1,
title: 'New Column',
status: 'new',
edit: true,
};
console.log(this.state.columnsData);
this.setState({
columsData: newColumn,
});
console.log(this.state.columsData);
};
}
CodePudding user response:
Your main issue is the way you update your state. This is what you have:
this.setState({
columsData: newColumn,
});
This piece of code will set the state to columsData: newColumn
, which is wrong for a few reasons:
- columsData should be columnsData
- You are overwriting the whole state with only your columns
- Your piece of code will remove all the other columns and replace it with only one.
Here is what it should be:
this.setState({
columnsData: [...this.state.columnsData, newColumn],
});
This will keep your current state, and add the new column to your existing list.
CodePudding user response:
You have a typo in columsData
. Additionally columnsData
should be an array so you probably need to set the new state to the old one plus the new column.
e.g. something like:
this.setState({
columnsData: [...this.state.columnsData, newColumn],
});
CodePudding user response:
this.setState({
if(this.state.columnsData && this.state.columnsData.length>0)
{
columnsData: [...this.state.columnsData, newColumn],
}
});