I have a parent component that maps over a list state using an Input component
import "./styles.css";
import { useState, useEffect } from "react";
import Input from "./Input";
export default function App() {
const [list, setList] = useState([{}]);
useEffect(() => {
console.log("list", list);
}, [list]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{list.map((_, i) => (
<div key={i}>
<Input id={i} setList={setList} />
</div>
))}
</div>
);
}
Submitting each Input leaves another Input available for submission. However, when I delete each Input, I see that the data object is gone but the UI doesn't reflect this.
import { useState } from "react";
const Input = ({ setList, id }) => {
const [value, setValue] = useState("");
const [submitted, setSubmitted] = useState(false);
const handleChange = (event) => {
const result = event.target.value.replace(/\D/g, "");
setValue(result);
};
const handleSubmit = () => {
setList((list) => [...list, { id: id, total: value }]);
setSubmitted(true);
};
const handleDelete = () => {
console.log("id", id);
setList((list) => list.filter((item) => item.id !== id));
};
return (
<div>
<input
value={new Intl.NumberFormat("ko-KR", {
style: "currency",
currency: "KRW"
}).format(Number(value))}
onChange={handleChange}
type="text"
/>
{submitted ? (
<button disabled={value.length === 0} onClick={handleDelete}>
Delete
</button>
) : (
<button disabled={value.length === 0} onClick={handleSubmit}>
Submit!
</button>
)}
</div>
);
};
export default Input;
I suspect that this is because
const [list, setList] = useState([{}])
Is initialized with an empty object, and that is causing the problem. However, I need at least one object inside the list state so I can have the initial Input component for submission.
How do I properly delete my Input component?
My codesandbox