Search code examples
javascriptreactjsfirebasegoogle-cloud-firestoreshortcode

Can i update firestore and storage of firebase in one line Code? using React js


I am updating firestore and Storage of Firebase React.js .

import "firebase/compat/storage";
import firebase from "config.js";

const [image, setImage] = useState();

firebase
  .storage()
  .ref("images/" + image.name)
  .put(image)
  .then(({ ref }) => {
    ref.getDownloadURL().then((url) => {
      firebase.firestore().collection("images").doc().set({ imageURL: url });
    });
  });

return (
  <input
    type="file"
    name="profile"
    onChange={() => setImage(event.target.files[0])}
  />
);

can we write this code to any other way. I mean, can I remove the repeating firebase. ?


Solution

  • I think you can use below code.I have tried the below example which uploads an image and returns the downloadURL and stores it in a Firestore document.I have used Firebase modular sdk v9, You can try the code below. It is in typescript you may change it to javascript if required.

    import { addDoc, collection } from "firebase/firestore";
    import { getDownloadURL, ref, uploadBytes } from "firebase/storage";
    import { useState } from "react";
    import { db, storage } from "./config/firebase";
    
    export default function App() {
      let downloadURL:string;
      const upload = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const selectedFiles = event.target.files as FileList;
        const dop = ref(storage, `${selectedFiles?.[0].name}`);
        const data = await uploadBytes(dop, selectedFiles?.[0]);
        downloadURL = await getDownloadURL(data.ref);
        console.log(downloadURL);
        const firestoreRef = collection(db, "images");
        const result = await addDoc(firestoreRef, {
          imageUrl: downloadURL
        });
        console.log(result);
      }
      return (
        <input
        type="file"
        name="profile"
        onChange={upload}
      />
      )
    }
    
    

    Also I can see you are using a deprecated version of Firebase Storage you can use the latest version which solves the multiple Firebase issues.

    You can try using React Firebase Hooks which provides convenience listeners for files stored within Firebase Cloud Storage.