Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)    
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading