'How to update a react state but only replace a particular object inside the array?
const filters = (type, value, status) => {
if(status === true) {
setSelectedFilters([...selectedFilters, {type, value, status}])
}
if(status === false) {
let filterStatus = selectedFilters.filter((obj)=>obj.value !== value)
setSelectedFilters(filterStatus)
}
if(type === 'price') {
if(value === 'min') {
setPriceValues({minPrice: status, maxPrice: priceValues.maxPrice ? priceValues.maxPrice : highestPrice})
}
if(value === 'max') {
setPriceValues({maxPrice: status, minPrice: priceValues.minPrice ? priceValues.minPrice : lowestPrice})
}
setPriceFilter({type, minPrice:priceValues.minPrice, maxPrice: priceValues.maxPrice})
//setSelectedFilters([...selectedFilters, priceFilter])
}
}
The filters function is passed into multiple filter components, such as 'categories', 'manufacturer' and 'prices'. I've already done the 'category' and 'manufacturer' filtering, but the "price" filtering is a bit more complicated, because I need to be able to filter by min and max price, and the filters function is invoked on input change.
I am trying to figure out how to add the price object from priceFilter into the selectedFilters state so I can then filter through it and only get the selected price. I struggle with finding a way to properly update the selectedFilters, because the function is invoked on every change of price. As you can see, I've used another state to create an object containing the prices, and it gets replaced onChange, but how do I now add priceFilters into selectedFilters on every invocation of the filters function?
If I do this setSelectedFilters([...selectedFilters, priceFilter]) then I'll be adding a new priceFilter obj on every change, and that's not what I want. I want to extract the selectedFilters again because it might contain other filter objects, BUT replace the priceFilter object only! How do I do that? Any ideas?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
