0

I want to create unique documents for each image I am uploading in a firebase collection.

This is my code for creating a document:

import { useState, useEffect } from 'react';
import { projectStorage, projectFirestore, timestamp } from '../firebase-config';

const useStorage = (file) => {
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState(null);
  const [url, setUrl] = useState(null);

  useEffect(() => {
    // references
    const storageRef = projectStorage.ref(file.name);
    const collectionRef = projectFirestore.collection('images');
    
    storageRef.put(file).on('state_changed', (snap) => {
      let percentage = (snap.bytesTransferred / snap.totalBytes) * 100;
      setProgress(percentage);
    }, (err) => {
      setError(err);
    }, async () => {
      const url = await storageRef.getDownloadURL();
      const createdAt = timestamp();
      await collectionRef.add({ url, createdAt });
      setUrl(url);
    });
  }, [file]);

  return { progress, url, error };
}

export default useStorage;

But I'm getting two documents, for one image.

the post the duplicate post

1 Answers1

-1

Every time you call collectionRef.add it creates a new document with its own unique ID. If you want something to be unique within a collection, it is best to use that value as the document ID within that collection and set the document based on that ID rather than adding a new document each time.

So for example:

await collectionRef.doc(new firebase.firestore.FieldPath(url)).set({ url, createdAt });

Now the URL is used to identify the document, so by definition there will be only one document for each unique URL.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • thank you for the answer, but now i'm facing a new trouble, no document is being created now – user16362778 Jan 03 '23 at 15:07
  • yes your answer definitely made sense, but whenever I am using Fieldpath, I'm facing a new error : Uncaught (in promise) TypeError: Class constructor FieldPath cannot be invoked without 'new' at Observer.complete – user16362778 Jan 04 '23 at 06:13
  • That seems like a typo in my answer. Did you try to fix that by adding `new` in front of `firebase.firestore.FieldPath` as the error message says? – Frank van Puffelen Jan 04 '23 at 15:23