I have 2 functions. One is getting called when I type on the search input. The second one is getting called when I select a category. Default value for search is '' and for selectedCategories null. However when I type first time or click category first time. First time the functions are getting called with the default values of both states. It looks like I am always 1 step before the right one.
const onTextChanged = (e: ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setIsComponentVisible(true);
setSearch(value);
};
const selectCategory = async (category) => {
const { id } = category;
if (!selectedCategories || !selectedCategories[id]) {
setCategories((prevState: any) => ({
...prevState,
[id]: category
}));
} else {
setSelectedCategories((prevState: any) => {
const { [id]: undefined, ...rest } = prevState;
return rest;
});
}
};
What is wrong and how it can be fixed?
If you are trying to console.log() your states, right after your state setter is called, your state probably would not be updated by then because React sets the state asynchronously. useEffect can help you with that, you can console.log() your state every time it changes. Something like this:
useEffect(() => {
console.log(search)
}, [search])