Home  >  Q&A  >  body text

Update next-auth session object in response to user's patch request update

<p>I searched the Internet for a long time but didn't find the answer. There are some ways to fix this, but they didn't work for me when I tried them. So, when a user logs in and a session is created, how do I update the new data in that session object after the user is updated via a patch request on the API backend. Thank you all for your replies and time. </p> <p>I tried various "tricks" I found online, and they worked for some people, but not for me. I want the session object to be updated after patch is called and user data is updated. </p>
P粉748218846P粉748218846443 days ago554

reply all(1)I'll reply

  • P粉481815897

    P粉4818158972023-08-27 09:17:05

    So I wrote an article on Medium about how to fix this problem: How to use useSession() Hook to update user session data in NextAuth

    import { useSession } from 'next-auth/client';
    
    export default function UserInfo() {
      const { data: session, update } = useSession();
    
      const handleUpdateUser = async () => {
        const newSession = {
          ...session,
          user: {
            ...session?.user,
            email: "someone@example.com"
          },
        };
    
        await update(newSession);
      };
    
      return (
        <button onClick={handleUpdateUser}>
          更新用户
        </button>
      );
    }

    reply
    0
  • Cancelreply