Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Both states are getting updated only after the second event call in React

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!