Home > database >  Cannot upload id by using uuid on firebase with React.js
Cannot upload id by using uuid on firebase with React.js

Time:10-15

Here is my function on JS, the issue is uuid would be saved as text like photos below by using .ref('posts/${id}')

According to photo 3, the uuid is working correctly, so I assume that there are some simple code mistakes on my "sendPost".

If you are good at JS and this type of issue, that would be grateful to be indicated.

import { v4 as uuid } from 'uuid';

const sendPost = () => {
    const id = uuid();
    const uploadTask = storage
      // eslint-disable-next-line no-template-curly-in-string
      .ref('posts/${id}')
      .putString(cameraImage, "data_url");

    uploadTask.on(
      "state_changed",
      null,
      (error) => {
        //error func
        console.log(error);
      },
      () => {
        //Complete func
        storage
          .ref("posts")
          .child(id)
          .getDownloadURL()
          .then((url) => {
            db.collection("posts").add({
              imageUrl: url,
              username: "TEST",
              read: false,
              //profile picture
              timstamp: firebase.firestore.FieldValue.serverTimestamp(),
            });
            history.replace("/chats");
          });
      }
    );
  };

firebase inside photo

uuid working check photo

CodePudding user response:

This ${id} in this code is just a string:

const uploadTask = storage
  // eslint-disable-next-line no-template-curly-in-string
  .ref('posts/${id}')

The no-template-curly-in-string actually says exactly what is going on: a string in '' cannot contain so-called template variables like {$id}. Or well, it can contain that string, but JavaScript will not replace that with the value of id.


If you want the ${id} to be interpreted as the value of the id variable, using backticks around the string instead of quotes:

const uploadTask = storage
  .ref(`posts/${id}`)

Alternatively, you can use classic string concatenation:

const uploadTask = storage
  .ref('posts/' id)

Or use Firebase's child() function:

const uploadTask = storage
  .ref('posts').child(id)
  • Related