Google Firebase user.PhotoURL doesn't Change After Upload

Viewed 147

I've been trying to figure out how to update the user photo after uploading it to Google Firebase. The user photo uploads to Firebase, however doesn't chance after uploading. Only it changes when the page is refreshed.

Is there a way to refresh the user profile photo without refreshing the whole page?

import { useEffect, useState } from "react";
import { useAuth, upload } from "./firebase";

export default function Profile() {
  const currentUser = useAuth();
  const [photo, setPhoto] = useState(null);
  const [loading, setLoading] = useState(false);
  const [photoURL, setPhotoURL] = useState("https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png");

  function handleChange(e) {
    if (e.target.files[0]) {
      setPhoto(e.target.files[0])
    }
  }

  function handleClick() {
    upload(photo, currentUser, setLoading);
  }

  useEffect(() => {
    if (currentUser?.photoURL) {
      setPhotoURL(currentUser.photoURL);
    }
  }, [currentUser])

  return (
    <div className="fields">
      <input type="file" onChange={handleChange} />
      <button disabled={loading || !photo} onClick={handleClick}>Upload</button>
      <img src={photoURL} alt="Avatar" className="avatar" />
    </div>
  );

Code is taken from LogicismX GitHub page.

1 Answers

I'm not too sure on what the upload() function does, you should include it but anyway:

Reading the docs might help, as you'll see there, after the app initialisation you want to export the firestore database as so

const app = initialiseApp(firebaseConfig)
export const db = getFirestore(app)

Then, in your file where you're trying to render the image, you should change your "read" function to onSnapshot(), this will run every time there's a change in said document in the database, only re-rendering whatever stateful variables you're making change per shapshot

here's an example:

import {onSnapshot, doc} from 'firebase/firestore'

import { db } from './firebaseConfig'

...

onSnapshot(doc(db, '<your-collection-name>', '<your-doc-name>', (snapshot) => {
  setPhotoUrl(snapshot.data().photoURL)
}
Related