Search code examples
reactjserror-handlingfetch-apireact-state

ReactJs - Can't setState from ERR_CONNECTION_REFUSED error inside fetch catch


I'm trying to set the error dynamically inside the catch, if any errors occur (in this case I'm simply trying to catch ERR_CONNECTION_REFUSED, as I do not have my localhost:8080 up on purpose)

const [error, setError] = React.useState("");

async function login(email, password) {
    await fetch("http://localhost:8080/auth/login", {
      method: "POST",
      body: {
        email: email,
        password: password,
      },
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        response.json();
      })
      .then((data) => {
      })
      .catch((error) => {
        console.log("Error from server");  <-- I can see this
        setError("Error from server");
      });
  }

The error is not set, as I can't see it inside my Typography element being rerendered. I know there might be issues with setting state inside an async function like fetch, but I can't find a solution online that tells me how to do it.

I also tried with useEffect, putting inside just the setError(error) and dependency [error], because I thought that maybe the fetch promise would setError any moment after its execution (but not instantaneously), thus changing the error any moment and useEffect would trigger, but it's still not working.

Also tried with separate members of fetch, without arrow functions:

try{
   const response = await fetch(...)...
} catch(error){
   setError("Error from server");
}

still not working. Am I missing something?


Solution

  • I believe the setError() is working, I checked it by putting the error in the alert() method and it popped up with the error message "Error from server". Below is the code:

        import React, { useState } from "react";
    
    export const Test = () => {   const [error, setError] = useState("");
    
      async function login(email, password) {
        await fetch("http://localhost:8080/auth/login", {
          method: "POST",
          body: {
            email: email,
            password: password,
          },
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
        })
          .then((response) => {
            response.json();
          })
          .then((data) => {})
          .catch((error) => {
              console.log("Error from server");
              setError("Error from server");
            });
        }
        
        login("[email protected]", "iamthepassword");
        
        alert(`This is the error message: ${error}`)
    
      return <div>{error}</div>; };
    

    This is the message that it displays: enter image description here