2

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?

3
  • Can you also post how you use the response status and how you intend to use the response content? Commented Dec 29, 2021 at 19:17
  • @kingkupps I am trying to show an error or success message and add appropriate color property dynamically based on the response status. The response content is irrelevant. I have already implemented a workaround by just putting my logic inside the first then block (since I am not using the response content). But still want to understand this particular case. Commented Dec 29, 2021 at 19:27
  • Please edit this information to your question. Commented Dec 29, 2021 at 20:20

1 Answer 1

2

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])
Sign up to request clarification or add additional context in comments.

2 Comments

Hi. Can you say that exactly which codes must place in the 'useEffect'?
this part should be in useEffect to be invoked after re-render : if (status === 200) { console.log("OK") } else { console.log("Something went wrong") }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.