0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NEXT.js+Auth.jsでユーザー情報を更新時にsessionのユーザー情報も更新する

Posted at

NEXT.js+Auth.jsでwebアプリを作っていて
ユーザー情報を更新し時に、sessionのuserの情報も更新する処理を実装するのに
なかなか答えに辿りつけず困ったので備忘録を書き残します。

前提条件

私は、Credentialでのログイン方式を採用していたので、
それ以外の方式では参考にならないかもしれません。

auth.tsにsessionが更新された時の処理を加える

callbacksに、次の処理を加えてください

auth.ts
 callbacks: {

    async session({ session, token }) {
      //他の処理//
    
        //sessionの更新処理
        //バックエンドからユーザー情報を取得する関数(プロジェクトに応じて書き換えてください)
        const userDBPromise = fetchUser();
        const userDB = await userDBPromise;
        //DBの最新の情報に上書き
        session.user = { ...session.user, ...userDB };
      
      return session
    },
},

sessinoの更新

page.tsx

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

export default function MyProfileUpadate() {

    //session更新のためupdateを呼び出し
    const {data:session,update} = useSession();

    async function onSubmit(){
        //ユーザー情報を更新する処理
        const res = update();
        if(res){
            //ここでupdateを実行するとsessionのuser情報が更新されます
            update();
        }
    }
    
    return(
        <form>
            //省略
            <button onClick={onSubmit()}>更新<button>
        <form>
    )
}

以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?