I have input number in which I specify a number that stands for the number of rendered components. For this I have two states with a number and an array. In the array I just pass one value with id
.
The code in useEffect
is not working correctly. When I click on button up
in input number, I always get the same item twice. And when I click on button down
, the items are not deleted.
Where did I go wrong here?
It should also be localStorage
in the code.
<code>const [Quantity, setQuantity] = useState('0')
const [Arr, setArr] = useState([])
useEffect(() => {
[...Array(parseInt(Quantity))].map((_, i) => {
setArr((prev) => {
const Item = { id: i };
localStorage.setItem("LSKey", JSON.stringify([...prev, Item]))
return [...prev, Item];
});
});
}, [])
<input type="number" value={Quantity || ""} min={0} onChange={(event) => {
setQuantity(event.target.value)
}} />
</code>
<code>const [Quantity, setQuantity] = useState('0')
const [Arr, setArr] = useState([])
useEffect(() => {
[...Array(parseInt(Quantity))].map((_, i) => {
setArr((prev) => {
const Item = { id: i };
localStorage.setItem("LSKey", JSON.stringify([...prev, Item]))
return [...prev, Item];
});
});
}, [])
<input type="number" value={Quantity || ""} min={0} onChange={(event) => {
setQuantity(event.target.value)
}} />
</code>
const [Quantity, setQuantity] = useState('0')
const [Arr, setArr] = useState([])
useEffect(() => {
[...Array(parseInt(Quantity))].map((_, i) => {
setArr((prev) => {
const Item = { id: i };
localStorage.setItem("LSKey", JSON.stringify([...prev, Item]))
return [...prev, Item];
});
});
}, [])
<input type="number" value={Quantity || ""} min={0} onChange={(event) => {
setQuantity(event.target.value)
}} />
render components
<code>Arr.map((Item) => (
<Components key={Item.id} id={Item.id} />
))
</code>
<code>Arr.map((Item) => (
<Components key={Item.id} id={Item.id} />
))
</code>
Arr.map((Item) => (
<Components key={Item.id} id={Item.id} />
))