Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if item exists in array React

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>
    )

  }
}
like image 733
tom harrison Avatar asked Jul 24 '17 09:07

tom harrison


1 Answers

it should be:

handleCheck(val) {
    return this.state.data.some(item => val.name === item.name);
}

because val here is an Object not a String.

Check this out: https://www.webpackbin.com/bins/-Kpo0Rk6Z8ysenWttr7q

like image 124
BnoL Avatar answered Oct 01 '22 06:10

BnoL