I am creating a shopping cart lit application, in that program add functionality is fine but when I add one list then another
enter code here
and then remove the one that is fine but when you want to delete two that is not able to deleted, also using the key={index} for identify each elements so what is the problem?

import { useReducer, useRef } from "react";
export default function App() {
const inputRef = useRef();
const [items, dispatch] = useReducer((state, action) => {
switch (action.type) {
case "add":
return [
...state,
{
id: state.length,
name: action.name
}
];
case "remove":
return state.filter((x) => x.id !== action.index);
default:
return state;
}
}, []);
function handleSubmit(e) {
e.preventDefault();
if (inputRef.current.value !== "") {
dispatch({
type: "add",
name: inputRef.current.value
});
}
inputRef.current.value = "";
}
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input ref={inputRef} />
</form>
<ul>
{items.map((item, index) => (
<li key={index}>
{item.name}
<button onClick={() => dispatch({ type: "remove", index })}>
X
</button>
</li>
))}
</ul>
</div>
);
}
The original
idof an item is based on the current length of the array, so theidand theindexof the item are identical. As soon as you delete an item from the start/middle of the items, the indexes of all items after no longer match theid. Instead use theidand not the index, whenever you wish to remove an item.In addition, don't depend on the length of the array, since deleting an item, and then adding another one would cause two items to have the same
id. Use auuidlibrary or the native Crypto.randomUUID():