Rajat Srivastava
Rajat Srivastava

Reputation: 125

Data not reflected on UI when deleting item from array

// Delete Input Fields:-
const [salesProduct, setSalesProduct] = useState(props.inputValue);

const deleteInput = (id, indexValue) => {
 salesProduct.splice(indexValue, 1); // salesProduct is an array when delete 
 let data = salesProduct;
 // when console the data it is giving write out put but data is not reflecting 
 console.log(data);  
 setSalesProduct(data);
}

// Below is My Jsx where i am using deleteInput event To Delete Item can any one please help me what i am doing wrong
salesProduct.map((value, index) => {

return (
<tr key={value.id}>    
<td scope="row">
<input id={value.id} value={value.shippingValue}  onChange={ (e) => handleInputAndDropdown(e, value.id, 'cartValue') } className={value.className} type={value.type} name={value.name} title={value.title} placeholder={value.placeholder} />
</td>    
<td>
 <input id={value.id} value={value.taxValue}  onChange={ (e) => handleInputAndDropdown(e, value.id, 'taxValue')}  className={value.className} type={value.type} name={value.name} title={value.title} placeholder={value.placeholder}/>
</td>    
<td>
{showDeleteBtn && <a href="#" onClick={() => deleteInput(value.id, index)}>Delete</a>}
</td>

</tr>
)
})

Upvotes: 0

Views: 368

Answers (2)

What I would do is totally different instead of splice I would go with a filter method

// Delete Input Fields:-
const [salesProduct, setSalesProduct] = useState(props.inputValue);

const deleteInput = (id) => {
  const newSales = salesProduct.filter(sale => sale.id != id); 
  setSalesProduct(newSales);
}

It would help you returning a new array, instead of the splice that remove the one you wish and return the value to you

Upvotes: 2

Kedel Mihail
Kedel Mihail

Reputation: 151

I can't see your full jsx code, but what you are probably doing is mapping each salesProduct to some html element. If your code looks something like that

function App() {
  return (
    <div className="App">
      {salesProduct.map((item, index) => (
        <div key={index}>
          {item}
        </div>
      ))}
    </div>
  );
}

E.g. if in the part of your UI where you display salesProduct(s) you map each salesProduct to some div element and the key of that div is the index of the sales product then you're doing it wrong because, as stated in the React docs the key must be completely unique, you can read here on why it's bad to use the index as key

P.S It is very hard to help when I don't see the code in which all the salesProduct are being rendered, so please provide some more information.

Upvotes: 0

Related Questions