'State array not updating when removing an array item in React
When I remove an array item from my state array, I'm also updating the prices after removing the array item. But prices are not updating. I have tried every thing, but didn't get any solution.
export default function CustomizerState(props) {
const initialTextItem = {
text: "Hello",
neonPrice: 0,
backplatePrice: 0,
neonPower: 0,
totalPrice: 0
}
const [settings, setSettings] = useState({
textItems: [initialTextItem],
libraryItems: [],
accessories: [...],
finalPrice: null
})
const removeItem = (id, itemType = "textItems") => {
const filteredItems = settings[itemType].filter((item) => {
return item.id !== id
})
setSettings((prevState) => (
{...prevState, [itemType]: filteredItems}
))
finalPrice()
}
const finalPrice = () => {
const textItemsPrice = getTotalPrice()
const libraryItemsPrice = getTotalPrice("libraryItems")
const accessoriesPrice = getTotalPrice("accessories", "unitPrice")
console.log(textItemsPrice, libraryItemsPrice, accessoriesPrice)
const finalPrice = textItemsPrice + libraryItemsPrice + parseInt(accessoriesPrice)
setSettings((prevState) => (
{...prevState, finalPrice}
))
}
const getTotalPrice = (itemType = "textItems", priceKey = "totalPrice") => {
let price = 0
settings[itemType].map((item) => (
price = price + (item[priceKey] * item.quantity)
))
return price
}
return (
<CustomizerContext.Provider value={{settings, addTextItem,
removeItem}}>
{props.children}
</CustomizerContext.Provider>
)
}
For now, it is behaving like when I remove any item, it doesn't update the finalPrice object item, but when I remove another item then it updates the prices for previous items. I don't know why it is behaving like this.
Can someone please have a look on my code and tell me what is wrong with it and how can I fix this?
Solution 1:[1]
You're calling finalPrice()right after you set your state
that triggers a re-rendering. You have to trigger the change using useEffect hook like this:
useEffect(() => {
finalPrice()
}, [settings]
You should probably consider separating your price from the rest of your settings.
Solution 2:[2]
Instead of calling a function right after updating the list, do the calculations before and update the state altogether. The problem with your approach is that when the calculus is being made, the state haven't updated yet, so when the function finalPrice() runs it takes the previous value.
I sincerely recommend you to use a Reducer instead, a single state with so many parameters may be troublesome.
Refer to useReducer, it will make your life easier.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DᴀʀᴛʜVᴀᴅᴇʀ |
| Solution 2 | DᴀʀᴛʜVᴀᴅᴇʀ |
