My code
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const MAX_QUANTITY = 10;
const MIN_QUANTITY = 0;
const [count, setCount] = useState(0);
const [items, setItems] = useState([{ id: 0 }]);
const addItem = () => {
setItems([
...items,
{
id: count + 1
}
]);
console.log(items);
};
const minusItem = () => {
setItems([{ id: 0 }])
console.log(items);
}
function add() {
if (count < MAX_QUANTITY) {
setCount(count + 1);
addItem();
}
}
function minus() {
if (count > MIN_QUANTITY) {
setCount(count - 1);
minusItem()
}
}
return (
<div className="App">
<h1>{count}</h1>
<button onClick={add}>+</button>
<button onClick={minus}>-</button>
</div>
);
}
My issue is that whilst I can consistently add an item to my items array, I am not able to remove the previous added item when the '-' button. As a test I set the 'minusItem' function to set the array back to it's initial state but you will notice that after the '-' button is pressed another object is added to the array before it is set, why is this?
I am just trying to add and subtract items to the array when either the '+' or '-' buttons are pressed. any suggestions on how to do this are most appreciated.
const {useState} = React;
function App() {
const MAX_QUANTITY = 10;
const MIN_QUANTITY = 0;
const [count, setCount] = React.useState(0);
const [items, setItems] = React.useState([{
id: 0
}]);
const addItem = () => {
setItems([
...items,
{
id: count + 1
}
]);
console.log(items);
};
const minusItem = () => {
setItems(prevItems => prevItems.slice(0, -1));
console.log(items);
}
function add() {
if (count < MAX_QUANTITY) {
setCount(count + 1);
addItem();
}
}
function minus() {
if (count > MIN_QUANTITY) {
setCount(count - 1);
minusItem()
}
}
return ( <
div className = "App" >
<
h1 > {
count
} < /h1> <
button onClick = {
add
} > + < /button> <
button onClick = {
minus
} > - < /button> <
/div>
);
}
// Render it
ReactDOM.render(
<App />,
document.getElementById("react")
);
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="react"></div>
pop()the last element in the array and update the state.