Reputation: 3129
This is probably a really stupid, facepalm inducing question...
Any reason why when I run this code (from a checkbox) it would replace the "errors" list as well as the "displayErrors" list. I am keeping my list in two places so I can filter and then bring back the original list.
constructor(props) {
super(props);
this.state = { date: new Date(), errors: [], displayErrors: [], onlyErrors: false };
}
filterErrors() {
// I would have placed a dataset in both "errors" and "displayErrors"
console.log(this.state);
let err = this.state.errors;
err.Stock = [];
this.setState({displayErrors: err });
console.log(this.state);
}
Upvotes: 2
Views: 216
Reputation: 2928
You need to combine your current errors using Object.assign()
:
Example taken from the site:
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
Object.assign()
will change the targeted object that you included as parameter, so I think what you need to do is something like Object.assign({}, error_lists, new_error)
in which you have an empty object added with your existing and new error object to create a new object.
Upvotes: 0
Reputation: 3343
What do you see when you console.log(err.Stock)? Prior to setting it to an empty array of course.I suspect undefined. Dot (".") syntax is used to access attributes of an object(behaviour or state). An array doesn't have attributes as such, it is an ordered set of objects. I suspect you need to iterate over your array and return the Stock object(not sure how to do this without knowing more about the Stock object). Then set the Stock object equal to an empty array.
Upvotes: 0
Reputation: 4415
It's happening because the arrays are objects and when you set err.Stock to be [], it's actually setting this.state.errors to be [] as well. you need to make a copy of your object somehow instead (without knowing what your object is I can't really help with that).
Also you shouldn't be console logging the state after calling setState, setState is asynchronous so the log may or may not print out the new state.
Upvotes: 1