Jin
Jin

Reputation: 1439

Firebase Storage: Invalid argument in `ref` at ind…child path but got a URL, use refFromURL instead

I have this code to create constant for image ref and product

export const createProduct = async (productData, image) => {
  const imageTimestamp = Date.now().toString();
  const newImageRef = await firebaseStorage
    .ref(`/images/${imageTimestamp}`).toString();
  const newProductRef = await firebaseDb.ref("products");
  const uploadTask = await firebaseStorage
    .refFromURL(newImageRef)
    .put(image)
  if (uploadTask.state === "success") {
    const url = await firebaseStorage
      .ref(newImageRef)
      .child(imageTimestamp)
      .getDownloadURL()

    const result = {
      ...productData,
      image: url,
    };
    const postRef = firebaseDb.ref(newProductRef).push();
    return postRef
      .set(result)
      .then((product) => {
        return {
          product,
          status: "ok"
        };
      })
      .catch(() => ({ status: "error" }));
  }
  return { status: "failure" };
};

But I got this error

Firebase Storage: Invalid argument in ref at ind…child path but got a URL, use refFromURL instead.

Where I am wrong with this, please help me

Upvotes: 0

Views: 534

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599766

From the error message is looks like you're passing a download URL into a call to child(...). The child() method can only be used with relative paths, like child("dir") or child("image.jpg"). If you have a full download URL, use firebaseStorage.refFromURL(...)


On second though, it looks like you're doing some weird stuff with the StorageReference instances. This should be a lot closer:

  const imageTimestamp = Date.now().toString();
  const newImageRef = await firebaseStorage.ref(`/images/${imageTimestamp}`);
  const newProductRef = await firebaseDb.ref("products");
  const uploadTask = await newImageRef.put(image)
  if (uploadTask.state === "success") {
    const url = await newImageRef.getDownloadURL()
    ...

Upvotes: 1

Related Questions