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

119
Views
Changing state inside async function in React

Consider the following scenario:

const ExampleComponent = () => {

    const [status, setStatus] = useState(500)

    //Calling this function with a click event
    const submitHandler = () => {

        const url = 'localhost:8000/foo'

        fetch(url)
            .then((res) => {
                setStatus(res.status)
                return res.json()
            })
            .then((res) => {
                if (status === 200) {
                    console.log("OK")
                } else {
                    console.log("Something went wrong")
                }
            })
    }
}

In this case, since React queues the setStatus task, by the time I'm making the status === 200 check, the status has not been updated. So how do we work around such scenarios?

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

0

Of course it will print ("Something went wrong"). Because your component isn't updated yet. In order to check your answer. run this code and look at your console to find out more :

import React, { useState } from 'react';

const App = () => {

    const [status, setStatus] = useState(500);

    const submitHandler = () => {

        const url = 'https://www.irdevprogs.ir/api/tsetmc/companies'

        fetch(url)
            .then((res) => {
                setStatus(res.status)
                return res.json()
            })
            .then((res) => {
                console.log(status)
                if (status === 200) {
                    console.log("OK")
                } else {
                    console.log("Something went wrong")
                }
            })
    }


    return (
        <div>
            <button onClick={submitHandler}>first</button>
            <button onClick={()=> console.log(status)}>second</button>
        </div>
    );
};

export default App;

But what is the solution: The standard routine of the React library says that you can not setState and use the updeted state concurrent. You sholud use useEffect hook to handle this. And add the status to the dependency array to handle this case. something like this :

useEffect(() => {
          if (status === 200) {
                console.log("OK")
            } else {
                console.log("Something went wrong")
            }
     
}, [status])
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!