I'm trying to check if an item exists in my array data
and if it does then prevent it from being added to the array.
The handleCheck
function will return true if an items already exists in the array but I'm not sure how to then use this to prevent the item from being added to the array.
I have attempted to use it in the handlePush
function this.handleCheck(item) == false ?
it should check if it's false and if so then push, if it returns true it should say it exists but at the moment this is not working as it will push to the array even if the item exists and it will never console.log 'exists`
How can I change my handlePush function to use handleCheck and prevent an item that already exists in the array to be added again?
https://www.webpackbin.com/bins/-KpnhkEKCpjXU0XlNlVm
import React from 'react'
import styled from 'styled-components'
import update from 'immutability-helper'
const Wrap = styled.div`
height: auto;
background: papayawhip;
width: 200px;
margin-bottom:10px;
`
export default class Hello extends React.Component {
constructor() {
super()
this.state = {
data: []
}
this.handlePush = this.handlePush.bind(this)
this.handleRemove = this.handleRemove.bind(this)
this.handleCheck = this.handleCheck.bind(this)
}
handlePush(item) {
this.handleCheck(item) == false ?
this.setState({
data: update(this.state.data, {
$push: [
item
]
})
})
: 'console.log('exists')
}
handleRemove(index) {
this.setState({
data: update(this.state.data, {
$splice: [
[index,1]
]
})
})
}
handleCheck(val) {
return this.state.data.some(item => val === item.name);
}
render() {
return(
<div>
<button onClick={() => this.handlePush({name: 'item2'})}>push</button>
<button onClick={() => this.handlePush({name: 'item3'})}>push item3</button>
{this.state.data.length > 1 ? this.state.data.map(product =>
<Wrap onClick={this.handleRemove}>{product.name}</Wrap>) : 'unable to map' }
{console.log(this.state.data)}
{console.log(this.handleCheck('item2'))}
{console.log(this.handleCheck('item3'))}
</div>
)
}
}