Search code examples
reactjsfirebasegoogle-cloud-firestorereact-reduxreactfire

Unhandled Rejection (FirebaseError): Function addDoc() called with invalid data


import React,{ useContext,useState } from 'react'
import "./style.css";
import { SignInBtn } from '../../componenets'
import { UserContext} from '../../contexts/user';
import AddAPhotoIcon from '@material-ui/icons/AddAPhoto';
import makeId from '../../helper/functions';
import { storage ,db } from '../../firebase';
import firebase from "firebase";


export default function CreatePost() {
    const [user, setUser] = useContext(UserContext).user;
    const [caption, setCaption] = useState("");

    const [image, setImage] = useState(null);

    const [progress, setProgress] = useState(0);

    const handleChange = (e) => {
        if(e.target.files[0]){
            setImage(e.target.files[0]);

            var selectedImageSrc=URL.createObjectURL(e.target.files[0]);
        
            var imagePreview =  document.getElementById("image-preview");

            imagePreview.src=selectedImageSrc;
            imagePreview.style.display="block";
        }

    };

    const handleUpload =() => {
        if(image){
            var imageName = makeId(10);
            const uploadTask=storage.ref(`images/${imageName}.jpg`).put(image);

            uploadTask.on("state_changed",(snapshot) =>{
                // progress function

                const progress=Math.round((snapshot.bytesTransferred/snapshot.totalBytes)*100);

                setProgress(progress);
            }, (error) => {
                console.log(error);
            }, () => {
                //get download url and upload the post info

             storage
            .ref("images")
            .child(`${imageName}.jpg`)
            .getDownloadURL()
            .then((imageUrl) => {

                   db.collection("posts").add({
                    timestamp: firebase.firestore.FieldValue.serverTimestamp(),
                    caption:caption,
                    photoUrl: imageUrl,
                    username: user.email.replace("@gmail.com",""),
                    profileUrl: user.photoUrl

                });
                })
            });
        }
    }; //handle upload check image exist

    return (
        <div className = "createPost">
           
        {user ? (
            <div className ="createPost__loggedIn">
            <p> Create Post </p>
            <div className ="createPost__loggedInCenter">
                <textarea className ="createPost__textarea"
                rows ="3"
                placeholder="Enter Caption Here"
                value ={caption}
                onChange = {(e) => setCaption(e.target.value)}    >            
                </textarea>

                <div className="createPost__imagePreview">
                  <img id="image-preview" alt="" />
                </div>
            </div>
           
            <div className="createPost__loggedInBottom">
            <div class ="createPost__imageUpload">
            <label htmlFor ="fileInput"><AddAPhotoIcon style = {{cursor:"pointer",fontSize :"20px"}}/>
            </label>
            <input id ="fileInput" 
            type ="file"
             accept ="image/*"
              onChange ={handleChange}/>
            </div>
            <button className = "createPost__uploadBtn" 
            onclick ={handleUpload} 
            style = {{color : caption ? "#000" : "lightgrey"}}>
                {`Upload ${progress !=0 ? progress: ""}`}
                </button>
            </div>
            </div>
            ) : (
                <div> 
                    <SignInBtn/>
                        <p style ={{marginLeft : "12px"}}> To post and Comment</p>
                </div> 
            )}

           
        </div>
    );
}

The problem is in this line

db.collection("posts").add

  

Am I missing something?

Now the thing is I am trying to make a clone of Instagram but the problem is all the things are working fine but there is the problem with a line below which gives an error that:

Unhandled Rejection (FirebaseError): Function addDoc() called with invalid data. Unsupported field value: undefined (found in field profileUrl in document posts/K5KaPhmXmT2nCHmFZb2i)

enter image description here

Thanks


Solution

  • Your uploaded document has two photoUrl fields.

    One of which is set using user.photoUrl which will always be undefined because the correct property name of a Firebase User object is photoURL (note capital letters). It is also possible that this property hasn't been set with an image, so you should make sure to check that before trying to store it.