更新数据库中的用户后如何更新 nextauth 会话?

问题描述 投票:0回答:1

我正在为会话使用凭据提供程序,我有一个数据库,我正在使用 prisma 保存用户。

但是在我更新用户之后,会话不会更新。

import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";

export async function POST(req) {
    const { email, langs, city } = await req.json();

    try {
        if (email && langs && city) {
            const result = await prisma.user.update({
                where: {
                    email,
                },
                data: {
                    email,
                    langs,
                    city,
                },
            });
            return NextResponse.json({ result });
        }

        return new Response(
            JSON.stringify({
                message: "User could not be updated!",
                ok: false,
            }),
            {
                status: 409,
            }
        );
    } catch (err) {
        console.log(err.message);
    }
}

这是我更新用户的代码。

prisma next next-auth
1个回答
0
投票

update() 方法现已可用。

useSession() 挂钩公开了一个

update(data?: any): Promise<Session | null>
方法,可用于更新会话,而无需重新加载页面。
您可以选择将任意对象作为第一个参数传递,该对象可在服务器上访问以与会话对象合并。
如果您没有传递任何参数,会话将从服务器重新加载。 (如果你想在服务器端突变后更新会话,比如在数据库中更新,这很有用。)

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

export default function Page() {
  const { data: session, status, update } = useSession()

  if (status === "authenticated") {
    return (
      <>
        <p>Signed in as {session.user.name}</p>
        
        {/* Update the value by sending it to the backend. */}
        <button onClick={() => update({ name: "John Doe" })}>
          Edit name
        </button>
        {/*
          * Only trigger a session update, assuming you already updated the value server-side.
          * All `useSession().data` references will be updated.
          */}
        <button onClick={() => update()}>
          Edit name
        </button>
      </>
    )
  }

  return <a href="/api/auth/signin">Sign in</a>
}
© www.soinside.com 2019 - 2024. All rights reserved.