Skip to content Skip to sidebar Skip to footer

Rename Multiple Images And Store In In Array React Native

I am working on react native project. I need to upload multiple images in firebase storage and also store their details in real time data database. I tried listing.images.forEach

Solution 1:

Try something like below:-

data["image"] = listing.images.map((image) => {
  return {
    name: "image" + Date.now(),
    type: "image/jpeg",
    uri: image
  }
});


Solution 2:

Using ordinary arrays should be avoided in the Realtime Database, you should instead store your array entries in a mapped object of some ID to the data.

In your current code, on each loop of the forEach you replace the existing data.images with the next entry in your array. You need to create new entries for each image. The "best practice" for this is to use Firebase's Push IDs, which can be generated using by calling const key = anyRef.push().key. Unlike const name = "image" + Date.now(), which can generate duplicate names if running fast enough, you won't be able to generate duplicate push IDs.

In addition, if you ever need to delete an image, you can just use the following without needing to mess with the indexes/keys of the other entries:

firebase.database().ref("listings")
  .child(listingId)
  .child("images")
  .child(imageId)
  .remove();

Applying this gives:

async function addListing(listing) {
  const listingsRef = firebase.database().ref("listings");
  const listingImages = {};
  
  const listingData = {
    sellerId: listing.sellerId,
    images: listingImages,
    // ...
  }

  listing.images.forEach((image) => {
    const key = listingsRef.push().key; // use firebase to generate a UUID
    listingImages[key] = {
      name: key,
      type: "image/jpeg", // <-- don't assume this
      uri: image
    }
  }

  return listingsRef.push(listingData);
}

Usage:

addListing(listing)
  .then(
    (ref) => console.log(`New listing #${ref.key} was created successfully!`),
    (err) => console.error(`Failed to create listing!`, err)
  )

Post a Comment for "Rename Multiple Images And Store In In Array React Native"