1

when user presses a button am just adding the data to an state, and now when user represses it i need to remove the data / and do not let the data to be added to the array ? Am using this on react native !

My state; 

state = { selected = [] };

Now the function to all data to state;

Handler(data){       
     cont {selected } = this.state;

        if(!selected.includes(data))
            {
                this.setState({ selected : [...selected, data] })
                
            }else{
                const index = selected.indexOf(data);
                if (index > -1) {
                    const selection = selected ;
                    selection.splice(index, 1);
                    this.setState({ selected : selection });
                }
            }
    }

But, above keeps on adding the data, as am sending the data as object

Data sent to above function, {available: 'true'}

So, how to do this ? check if the object already presented and remove it ? It works when i pass array like "[true]", but its not working when i pass object !

khristy_01
  • 37
  • 5
  • https://stackoverflow.com/questions/53748605/does-include-works-with-array-of-objects This will help regarding `includes` function which does the check. If the data is being added to the state, that means there is some problem with the condition right? check what includes offers to you. – Rush W. Jan 02 '21 at 07:47
  • You are mutating your state here `const selection = selected; selection.splice(...` you need to, at the very least clone the state array `const selection = [...selected];` but better to do it in the `setState` call `setState(prevSelected => *update logic*)` – pilchard Jan 02 '21 at 11:19

0 Answers0