So I am trying to set a value using a useState
hook (React JS) in an if-else
conditional statement.
I need to check whether there is addOnName
(which is passed as a parameter), in the addOnContainer
array and if it does, I need to deduct the addOnPrice
(which is also passed as a parameter) to the totalprice
using the setTotalPrice
(useState
hook).
If the addOnContainer
does not include the addOnName
, I have to add the addOnPrice
to the totalprice
.
The code works fine, as it gives me correct outputs in the chrome console. But when I try to use the useState
hook to set total price, only the if block runs, and the else
never runs no matter what the condition is.
I have tried moving the useState
out of the if-else
, and had no luck with that.
What am I doing wrong here? Note that this function is set to be executed when a checkbox is clicked.
const [totalPrice, setTotalPrice] = useState(200) function selectAddOn(addOnName, addOnPrice) { let temp = totalPrice if (!addOnContainer.includes(addOnName)) { temp = totalPrice + addOnPrice setTotalPrice(temp) } else { //never reaches even if the condition is false when useState is used. temp = totalPrice - addOnPrice setTotalPrice(temp) } }
Advertisement
Answer
At each rerender, let addOnContainer = [];
is getting reset to empty array.
You can use a useRef
to avoid it:
const {useState, useRef} = React function App() { const [totalPrice, setTotalPrice] = useState(200); const addOnContainer = useRef([]); // let addOnContainer = []; // This was the ISSUE function addToTotalPrice (addOnName, addOnPrice) { let temp = totalPrice; if(!addOnContainer.current.includes(addOnName)){ addOnContainer.current.push(addOnName); temp = totalPrice + addOnPrice; setTotalPrice(temp) } else { temp = totalPrice - addOnPrice; setTotalPrice(temp); } } return ( <button onClick={()=>addToTotalPrice('cheese',30)}>Click, totalPrice: {totalPrice}</button> ); } ReactDOM.render(<App />, document.body)
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>