You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为NextAuth登录功能设置加载状态?

问题描述

我提交表单时会调用signIn函数,所有操作都在后台完成,导致我没法给它设置状态。

我通过以下导入实现登录功能:

import { signIn } from "next-auth/react";

表单提交触发的处理函数:

const handleSubmit = async (e) => {
    e.preventDefault();
    const res = await signIn("credentials", {
        username: input.username,
        password: input.password,
        redirect: false,
    });
};

补充细节,我的[...nextauth].js API文件如下:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import dbConnect from "../../../util/mongodb";
import user from "../../../models/user";
import bcryptjs from "bcryptjs";

export default NextAuth({
    session: {
        strategy: "jwt",
    },

    providers: [
        CredentialsProvider({
            name: "credentials",
            credentials: {},
            async authorize(credentials, req) {
                await dbConnect();

                const { username, password } = credentials;
                const users = await user.findOne({ username: username });

                const decodedPassword = await bcryptjs.compare(password, users.password);

                if (!users) {
                    throw new Error("No such user in the database");
                }

                if (users.username === username && !decodedPassword) {
                    throw new Error("Password does not match");
                }

                if (users.username === username && decodedPassword) {
                    const { password, ...others } = users;
                    return {
                        id: users._id,
                        username: users.username,
                        firstname: users.firstname,
                    };
                }
            },
        }),
    ],
    pages: {
        signIn: "/auth/signin",
    },
    callbacks: {
        async session({ token, session }) {
            session.user = token.user;
            return session;
        },

        async jwt({ token, user }) {
            if (user) {
                token.user = user;
            }
            return token;
        },
    },
});

解决方法

1. 添加加载与错误状态控制

在组件内声明状态变量,手动控制登录过程中的加载状态、错误提示:

import { useState } from 'react';
import { signIn } from "next-auth/react";

export default function SignInForm() {
    const [input, setInput] = useState({ username: '', password: '' });
    const [isLoading, setIsLoading] = useState(false);
    const [errorMessage, setErrorMessage] = useState('');

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsLoading(true);
        setErrorMessage('');

        const res = await signIn("credentials", {
            username: input.username,
            password: input.password,
            redirect: false,
        });

        setIsLoading(false);

        // 根据返回结果更新状态
        if (res?.error) {
            setErrorMessage(res.error);
        } else if (res?.ok) {
            // 登录成功后的操作,比如跳转首页
            window.location.href = '/';
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <input
                type="text"
                value={input.username}
                onChange={(e) => setInput({...input, username: e.target.value})}
                placeholder="用户名"
                disabled={isLoading}
            />
            <input
                type="password"
                value={input.password}
                onChange={(e) => setInput({...input, password: e.target.value})}
                placeholder="密码"
                disabled={isLoading}
            />
            <button type="submit" disabled={isLoading}>
                {isLoading ? '登录中...' : '登录'}
            </button>
            {errorMessage && <p style={{color: 'red'}}>{errorMessage}</p>}
        </form>
    );
}

2. 全局监听登录状态(可选)

如果需要在其他组件中监听用户登录状态,使用useSession钩子:

import { useSession } from "next-auth/react";

export default function UserInfo() {
    const { data: session, status } = useSession();

    if (status === 'loading') {
        return <p>加载中...</p>;
    }

    if (status === 'authenticated') {
        return <p>欢迎,{session.user.username}</p>;
    }

    return <p>请先登录</p>;
}

内容的提问来源于stack exchange,提问作者crayonne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 10:16:10