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>
);
}