Brihaspati
Brihaspati

Reputation: 23

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?

Upvotes: 2

Views: 605

Answers (1)

Mohammad Taheri
Mohammad Taheri

Reputation: 464

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])

Upvotes: 2

Related Questions