Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to concatenate multiple values in react state array

I have created a todo list app I can add or remove elements in that list I am using react state for this purpose. Adding new element is perfectly working but removal isn’t whenever I click on remove it just remove everything except the last item I have added I am using removeItem method to perform this functionality and I am filtering that clicked value and map rest of values in this function and I have tried to print those values in console ad well and I am getting desired output in console but those values are not getting stored in state array and I don’t know why its happening:

import { useState } from 'react';
import './App.css';

let App = ()=>{

const [initial, addInitial] = useState('');
const [val, addVal] = useState([]);

  let changeHandler = (e)=>{
    addInitial(e.target.value)
  }

  let addItem =(event)=>{

      let newItem = initial;
      addVal( (prevValues) => [...prevValues, newItem]);
  }

  let removeItem = (par)=>{
 
    val.map((value, index)=>{
       if(index != par){
         addVal([ [...value] ])         
       }else{
         
       } 
    })

  }

    return(
    <div id="parent">
        <div id="container">
            <h1>To-Do List</h1>

          <div id="sub1">
            <input type="text" value={initial} onChange ={changeHandler} placeholder='Add a item' autoFocus/>
            <button id="add" onClick = {addItem}>+</button>
          </div>
          
            
          <div id="sub2">
            
            {
              val.map((name, index)=>{
                return(
                  <div id="cross" key={index}> 
                    <button className="remove" id={index} onClick = { ()=> removeItem(index)}>&#10060;</button>
                    {name}
                  </div>
                )})
            }

          </div>
        </div>
    </div>
    )
}

export default App;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Instead of using map method just use filter method to filter out the removed item

let removeItem = (par)=>{
  const arr = val.filter((item,index) => index != par)
  addVal(arr)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading