I have an event that gets triggered upon change. This event checks which filter has been changed and then updates the state accordingly.
If I was not using react hooks, I would have gone for something like this -
const target = e.target;
const value = e.type === "checkbox" ? target.checked : target.value;
const name = e.target.name;
this.setState({ [name]: value });
As you can see I would be able to update the state name using the [name] but since I am using react hooks I am not able to use the above. Instead I have got this -
const [type, setType] = useState("all");
const [capacity, setCapacity] = useState(1);
const [price, setPrice] = useState(0);
const [minPrice, setMinPrice] = useState(0);
const [maxPrice, setMaxPrice] = useState(0);
const [minSize, setMinSize] = useState(0);
const [maxSize, setMaxSize] = useState(0);
const handleChange = (e) => {
const target = e.target;
const value = e.type === "checkbox" ? target.checked : target.value;
const name = e.target.name;
switch (name) {
case "type":
setType(value);
break;
case "capacity":
setCapacity(value);
break;
case "price":
setPrice(value);
break;
case "minPrice":
setMinPrice(value);
break;
case "maxPrice":
setMaxPrice(value);
break;
case "minSize":
setMinSize(value);
break;
case "maxSize":
setMaxSize(value);
break;
default:
return;
}
};
What you have seen above does not work for some reason. When I trigger the filter it goes into the case as I have already tested this, but the state does not seem to update. The name and value have also been logged and they are fine too. I am not sure what is causing this and I am only new to programming so any help would be appreciated!
*** Just to reiterate the value and name are both working and so is the switch statement. It's just the state that is not updating ***