Home > Net >  Came across an error while working on the "edit" functionality inside normal array
Came across an error while working on the "edit" functionality inside normal array

Time:12-28

Apart from the targeted element, the remaining elements of the array are undefined (see the comment below). Expected the targeted element in the array to be overwritten while retaining rest of the array elements.I would like to know whether the issue arose due to my coding approach.



const Account=()=> {
    const[currentItem,setCurrentItem]=useState('')
    const[itemList,setItemList]=useState([])
    const[title,setTitle]=useState()
    const[status,setStatus]=useState(false)
    const[editId,setEditId]=useState()

    console.log(itemList)
    const addItemToList=()=>{
        if (status){ 

            setItemList(itemList.map((item,i)=>{   //Array undefined from here
                if(i===editId){
                    return itemList[i]=title
                }
            }))
            setTitle('')
            setStatus(false)   
        }else{
            setItemList([...itemList,title])
            setTitle('')
        }
    }
   
    const editHandler=(index)=>{
        const editTitle=itemList.find((item,i)=>i===index)
        setTitle(editTitle) 
        setStatus(true) 
        setEditId(index)
             
    }
    return (
        <div>
            <h1>Account</h1>            
            <input value={title} onChange={(e)=>setTitle(e.target.value)} type="text" placeholder="Enter"></input>
            <button onClick={addItemToList}>{status? 'Edit':'Add'}</button>
            <ul>
                {itemList.map((data,index)=>{
                    return(
                        <React.Fragment key={index}>
                            <li>{data}</li>
                            <button onClick={()=>deleteHandler(index)}>Delete</button>
                            <button onClick={()=>editHandler(index)}>Edit</button>
                        </React.Fragment>                        
                    )
                })}                    
            </ul>  
        </div>    
    )
}


CodePudding user response:

Since you are using map function, there must be an else statement just like the following.

 setItemList(itemList.map((item,i)=>{   //Array undefined from here
          if(i===editId){
              return itemList[i]=title
          }else{    // else statement missing
            return item
          }
      }))
  • Related