有了會員照片的url後,下一步就是要更新到會員資料庫裡面,更新資料的方式是使用到updateProfile的功能。
在onSubmit裡面多加了一個判斷,假如使用者沒有上傳圖片的話就不更新會員資料,有的話才將圖片url傳入資料裡面。
import { updateProfile } from "firebase/auth";
function Member(){
    const user = auth.currentUser
    const [photoURL,setPhotoURL] = useState(null)
    const [imageUpload, setImageUpload] = useState(null)
    const previewImg = imageUpload? URL.createObjectURL(imageUpload) : ""
    function onSubmit(){
        if(previewImg){
            const imagesRef = ref(storage, 'user-images/' + user.uid);
            const metadata = {
                contentType: imageUpload.type,
            };
            uploadBytes(imagesRef, imageUpload,metadata).then((snapshot) => {
                return getDownloadURL(snapshot.ref)
            }).then((url)=>{
                setPhotoURL(url)
            });
            updateProfile(user, {
                photoURL
            })
        }
    }
    return (
				//略
				<div className="imgwrap">
            <img src={user.photoURL&&previewImg?previewImg:user.photoURL} alt=""/>
        </div>
        <div className="editbtnwrap">
            <label className="btn_edit" htmlFor="upload" >上傳照片</label>
            <input type="file" accept="image/*" id="upload" 
                onChange={(e)=>setImageUpload(e.target.files[0])}
            />
        </div>
                   
    )
}
export default Member
這邊比較會有問題的地方是判斷使用者是否有圖片並依狀態顯示不同的照片,有以下兩個狀況 :
第一種狀況必須是user.photoURL和previewImg都有的時候,在點擊上傳後畫面要顯示他上傳的照片previewImg;第二種相對單純,只要有上傳就顯示previewImg,所以在img上面寫了這樣的判斷式src={user.photoURL&&previewImg?previewImg:user.photoURL}。