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

154
Views
State not updating in React Fetch function

I have a state, that is set to be either true or false in a fetch statement. When the fetch statement is called, the state is not updated until the second time the submit button is pressed.

It is because of that, that whenever I call an if statement right after, my code automatically navigates to my home page, thinking that the adding of a new account is successful.

When I try to set the state to null or false, the ternary statement automatically fires off as well.

I've checked the data by console logging it, and it comes back as "false" when applicable, but still never updates the state

Any insight on how to approach next?

Edit: The fetch is returning a boolean

    let navigate = useNavigate();

    // Error states
    const [successfulAdd, setSuccessfulAdd] = useState(true);


    // Function
    function handleRegister(e) {
        const user = { firstName, lastName, email, password, phone, userName, isAdmin };

        if (password !== passwordConfirm) {
            setPasswordMatch(false);
        } else {
            fetch("http://localhost:8080/user/add", {
                method: "POST",
                headers: { "Content-type": "application/json" },
                body: JSON.stringify(user),
            })
                .then(response => response.json())
                .then(data => setSuccessfulAdd(data));
        }

        if (successfulAdd) {
            navigate("../home");
        }
    }
.
.
.
    return (
.
.
.
         {/* Username Checker */}
         {successfulAdd ? "" : <div class="alert alert-danger" role="alert">
              The username you've entered has been taken
         </div>}
.
.
.
)

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

0

Since Fetch API and setState are both asynchronous, you might want to put the if statement and all logic inside .then(…)

fetch(…)
 .then(res => res.json())
 .then(json => … //navigate here)
 .catch(err => … //set your error state here)

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!