I have created a state to store all of my filters, however, the state is not changing properly even though I have used setFilter() on it. The state only changes after I select something else. This is where I initialize the state:
const [filter, setFilter] = useState({
a: 'ALL',
b: 12,
});
Here is the place where I filter everything:
const parseA = (e) => {
console.log('before', filter);
setFilter(prevValues => {
console.log('returning setFilter', {
...prevValues,
a: Number(e.target.value)
});
return {
...prevValues,
a: Number(e.target.value)
}
})
console.log('after', filter);
}
In my case, I am using an HTML form for the user to change the state.
<select value={filter['a']} onChange={parseA}>
<option onSelect={parseA}>8</option>
<option id="10">10</option>
<option id="12">12</option>
<option id="14">14</option>
</select>
After the user selects something, the state should change to what the user selected. However, it is not changing in the right way. The first time the user selects something, the state stays the same as before. The second time the user selects something, the state is now what the user previously selected.
Using the logs I have from above, I can see that the "returning setFilter" log is correct. However, both the "before" and "after" are the exact same!