In addition to this question
I am trying to map individually a state to another state to store the amountToPay
object to get the sum of it. The problem is every time it renders the onChange
function. It stores every state as object as you can see here: .
What I want to happen is to only get [434
] instead of ['','4','43','434']
So I can .reduce the array to get the sum.
My method on storing the array object to another state is this
const [amountToPay, setAmountToPay] = useState("")
console.log("AMOUNT TO PAY", amountToPay)
useEffect(() => {
serviceItem.map((item) => (
setAmountToPay([...amountToPay, item.amountToPay])
))
}, [serviceItem])
useEffect(() => {
serviceItem.map((item) => (
setAmountToPay([...amountToPay, item.amountToPay])
))
}, [serviceItem])
You can check the whole code here CodeSandbox code.Any help is appreciated 🙂
3
Answers
I was doing it the wrong way. I solved it by mapping the serviceItem then using
reduce
to get the sum instead of putting it again into a separate array of object then mapping it again to get the sum.Thanks for all the help and suggestion!
There are several things I suggest you to do:
serviceItem
. You can useUUID
,nanoid
, or evenDate.now()
const [amountToPay, setAmountToPay] = useState([]);
serviceItem
collection. In order to do this you need to create onChange handler, it will be something like thisAnd amount to pay can be easily got from
serviceItem
collection, without effects or other statesthis is happening because you are setting serviceItem on onChange method
and use passed serviceItem as deps array to useeffect in which you are setting amountToPay.
so on every change it’s appending in array
Rather then setting amount in useEffect, make a method and call on remove/add button so it will only call after user is finished typing. you can also place a button ‘Save’ or ‘calculate Amount’ and call handleSetAmountToPAY method which will update amount.