0

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>
    )
}

1 Answer 1

2

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)    
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.