I want to make sure that I can't push a duplicated value into an array in a React state. The duplicated value is still going in the array though.
I have tried using .includes
but it is not working.
const categoryCheck = (category) => {
let categories = [...this.state.categories]
if (this.state.categories === undefined) {
return
}
console.log(categories, category)
console.log(!categories.includes(category))
if (!categories.includes(category) === false) {
categories.push(category)
console.log('new category', categories)
}
}
input: 'cat'
Expected result: ['cat']
Actual result: ['cat', 'cat']
UPDATE: This is my function and this is how I call it. Thanks for all the help!
uniqueCategories = category => {
//makes sure that there are no duplicate categories in array
if (category === undefined) {
return;
}
let categories = new Set(category);
categories = Array.from(categories);
console.log(categories);
return categories;
};
I call it in another function like this:
this.setState({
categories: this.uniqueCategories([
...this.state.categories,
categoryInput
])