'NextJS not setting state on button click

I am having issues with my NextJS app. I am trying to display a class (loading spinner) to a button when it tries to log a user in. I am doing this by setting the loading state to true before it calls the login function, and then set the state to false after its done (in the submitForm function), but it doesn't seem to be setting it. Whenever i click the button the state stays at false. Any help would be greatly appreciated.

import { useAuth } from '@/hooks/auth'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import ButtonSpinner from '@/styles/buttonspinner.module.css'

export default function Home() {
    const router = useRouter()

    const { login } = useAuth({
        middleware: 'guest',
        redirectIfAuthenticated: '/dashboard',
    })

    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [errors, setErrors] = useState([])
    const [status, setStatus] = useState(null)
    const [loading, setLoading] = useState(false)

    useEffect(() => {
        if (router.query.reset?.length > 0 && errors.length === 0) {
            setStatus(atob(router.query.reset))
        } else {
            setStatus(null)
        }
    })

    const submitForm = async event => {
        event.preventDefault()

        setLoading(true)
        login({ email, password, setErrors, setStatus })
        setLoading(false)
    }

    return (
        <div>
            <form className="mt-8 space-y-6" onSubmit={submitForm} autoComplete="off">
                <button className={"shadow-sm relative w-full " + (loading ? ButtonSpinner['btn-loading'] : "")}>
                    Sign in
                </button>
            </form>
        </div>
    )
}


Solution 1:[1]

you are not waiting for login response

const submitForm = async event => {
  event.preventDefault()
  setLoading(true)
  try {
     await login({ email, password, setErrors, setStatus });
  } finally {
    setLoading(false)    
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bartosz Ciach