React: change state after fetch in functional component

I have the following component:

export default function SignIn()  {
    const [isLoading, setIsLoading] = useState(false);
    const classes = useStyles();
  
    const handleSubmit = (event) => {  
      event.preventDefault();
      if(!AuthService.login(event.target))
      {
        setIsLoading(false);
      }
      
    }

    return (
      <Container component="main" maxWidth="xs">
        <CssBaseline />
        <div className={classes.paper}>
          <Avatar className={classes.avatar}>
            <LockOutlinedIcon />
          </Avatar>
          <Typography component="h1" variant="h5">
            Sign in
          </Typography>
          <form className={classes.form} noValidate onSubmit={(event) => { handleSubmit(event); setIsLoading(true); }}>
            { isLoading ?
              <CircularProgress/> :
              <Button
              type="submit"
              fullWidth
              variant="contained"
              color="primary"
              className={classes.submit}
              >
                Sign In
              </Button>
            }  
          </form>
        </div>
      </Container>
    );
  }

When I submit the form, the “isLoading” becomes true, and the loading bars show up. Anyway if the “AuthService.login()” fails, the “isLoading” state is not updated.

What am I doing wrong?

Working code

The problem was related to the fact that

if(!AuthService.login(event.target))

is an async function, so I had to “await” for the response in order to evaluate it’s result.

The working code:

  async function handleSubmit (event) {  
    event.preventDefault();
    setIsLoading(true)
    try {
      await AuthService.login(event.target);
      setIsLoading(false)
    } catch (e) {
      console.log('Handle errors here');
    } finally {
      console.log('We do cleanup here');
    }
  }

Answer

Change:

onSubmit={(event) => { handleSubmit(event); setIsLoading(true); }}

to:

onSubmit={(event) => { handleSubmit(event) }}

Also change handleSubmit to:

 const handleSubmit = (event) => {  
      event.preventDefault();
      setLoading(true);
      if(!AuthService.login(event.target))
      {
        setIsLoading(false);
      }
      
    }