'How to push new column into array using setState
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);
};
}
Solution 1:[1]
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],
});
Solution 2:[2]
this.setState({
if(this.state.columnsData && this.state.columnsData.length>0)
{
columnsData: [...this.state.columnsData, newColumn],
}
});
Solution 3:[3]
Instead of
data.encode='UTF-8'
it should be:
data.encode('UTF-8')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben Stephens |
| Solution 2 | Tutorial Point Youtube Channel |
| Solution 3 | Marcin |
