Function handle filter still shows the previous state value after execution
…………………………………………………………………….
const [ageFrom, setAgeFrom] = useState('');
const [ageTo, setAgeTo] = useState('');
const filters = [
{
title: 'age from',
value: `${ageFrom} years old`,
state: ageFrom,
func: setAgeFrom,
},
{ title: 'age to', value: `${ageTo} years old`, state: ageTo,
func: setAgeTo },
]
const handleFilter = async () => {
const dataFilter = {
ageFrom,
ageTo,
};
console.log(ageFrom, ageTo);
};
return(
{filters.map((filter) => {
return filter.state !== '' ? (
<button className="flex whitespace-nowrap gap-4 bg-info items-center cursor-pointer border border-primary px-4 w-fit rounded-md" key={filter.title}>
<span>
{filter.title}: {filter.value}
</span>
<span
className="text-2xl"
onClick={() => {
filter.func('');
handleFilter();
}}
>
×
</span>
</button>
) : null;
})}
)
Function handle filter still shows the previous state value after execution
2
Answers
As per you code, initial state of
ageFrom
andageTo
is empty and you have added check that filter statefilter.state !== ''
is not empty then show the button else return null.As state is always empty string then it always return null so there is no UI on the screen
what you can do inOrder to make it work:
1 – either set some default value to state, or you need to update state in the else part.
2 – you need to pass some parameter in the click function instead of empty.
Note:
as you have added click on span then make sure you are clicking on the span only, click won’t work on button.
I have bit modified code so that you can understand what changes need to do. this code will you give some idea to make necessary changes as per your requirement.
https://react.dev/reference/react/Component#setstate
"Calling setState does not change the current state in the already executing code:
It only affects what this.state will return starting from the next render."
This might be the pitfall.