I am new to Javascript so probably I am lacking the fundamentals to solve this issue. I am trying different things, and reading tutorials, but so far no luck.
The objective is to modify the state, just by addding a new keyword to the array "keywords" that is contained inside the "blockOptions" object. I add a key/value for then using .map() or deleting the keyword if needing. I am also trying to use ES6 recommendations.
Here is the constructor:
blockOptions: {
...
keywords: [],
And here is the function I call from the component
onAddKeyword(e) {
if (e.key === "Enter") {
var newKeyword = {
text: e.target.value,
key: Date.now()
};
this.setState({
blockOptions.keywords: [...this.state.blockOptions.keywords, newKeyword]
});
console.log(this.blockOptions.keywords);
e.target.value = "";
e.preventDefault();
}
}
If I use this same code with an array that is not nested inside "blockOptions", everything works fine. Any suggestion about the code itself would be valuable as I am still new to JS.
Thanks for your help
this.state.blockOptionsis an object - you need tosetStatethe object as well:this.setState({ blockOptions: { keywords: ... } })onAddKeyword = (e) => {since it is an event function you might want to check whatthisis equal to. You might be setting the event.state to something and not the component.