0

I think this question is related to how React apps are written in general.


  • For user sessions I use - NextAuth.js
  • All user data (incl profile image) from NextAuth is stored on Supabase (PostgreSQL)

How to show user's new profile image across everywhere that uses it (without page refresh)?

Let's say:

  • I update user's profile image in a Settings page
  • The updated image is showing fine on Settings enter image description here
  • But the old image is still on the navbar (Navbar component), unless I refresh the page enter image description here

Settings page:

const Settings = (props: any) => {
  const { data: session } = useSession()
  const user = session?.user
  const [file, setFile] = useState<File | null>(null)
  const [image, setImage] = useState<string | null>(null)

  let uploadHandler = async (file: File) => {
    const formData: any = new FormData()
    formData.append('file', file)

    try{
      // assume I update the user (and their profile image) in the database here
      // and receive a url of the uploaded image here
      const { data } = await axios.post(......)
      setImage(data?.url)
    }
    catch (error){

    }
  }

  useEffect(() => {
    (async () => {
      if (file){
        await uploadHandler(file)
      }
    })();
  }, [file])

  useEffect(() => {
    setImage(user?.image!)
  }, [user])

  return (
    <>
      <Avatar src={image} />
      <FileButton onChange={setFile} accept="image/png,image/jpeg">
        {(props) => <Button {...props}>Upload photo</Button>}
      </FileButton>
    </>
  )
}

export default Settings

Navbar component:

export function UserAvatar(props: any) {
  const { data: session } = useSession()
  const user = session?.user

  return (
    <>
      ...
      <Avatar src={user?.image!} />
      ...
    </>
  );
}
aivarastee
  • 81
  • 2
  • 12
  • 1
    Where is setImage defined? – kennarddh Aug 06 '22 at 02:53
  • Updated just now. Forgot to add in example. – aivarastee Aug 06 '22 at 04:03
  • 1
    Does this answer your question? [Where and how to change session user object after signing in?](https://stackoverflow.com/questions/64576733/where-and-how-to-change-session-user-object-after-signing-in) – kennarddh Aug 06 '22 at 07:03
  • 1
    see this [discussion](https://github.com/nextauthjs/next-auth/discussions/3941), I think it's not possible yet but you may find a workaround in the discussion – mocherfaoui Aug 06 '22 at 08:25

1 Answers1

0

Figured it out!

There's a way to reload NextAuth sessions using this:

document.dispatchEvent(new Event("visibilitychange"))

Not sure if it's a good practice but it works. No need using this anymore:

const [image, setImage] = useState<string | null>(null)
aivarastee
  • 81
  • 2
  • 12