Troubleshooting asynchronous functions in Ionic3 when using Firebase Storage and Firestore

Attempting to retrieve the downloadURL from an uploaded image. The uploadImage function is used to upload the image to Firebase Storage.

uploadImage() {
  this.image = 'movie-' + new Date().getTime() + '.jpg';
  let storageRef: any,
  parseUpload: any;
  return new Promise((resolve, reject) => {
  storageRef = firebase.storage().ref('imgs/' + this.image);
  parseUpload = storageRef.putString(this.cameraImage, 'data_url');     
})

The goal is to save the image URL for retrieval from a Firestore document. This function is used to obtain the downloadURL after the image is uploaded.

If my understanding is correct, this method should return a string, as it needs to be saved in Firestore.

async getImgFromServer(imgName: string) {
  let img;
  let downloadIMG;
  img = firebase.storage().ref("/imgs/" + imgName).getDownloadURL();
  let ref= firebase.storage().ref();
  const imgRef = ref.child("/imgs/" + imgName);
  const downloadURL = await imgRef.getDownloadURL()
  return downloadURL
}

The challenge is ensuring that the second function (getImgFromServer()) executes only after the first one (uploadImage()) is completed. Once the URL is obtained, it is saved in the Firestore Cloud database using the updateImgFromServer function.

 updateImgFromServer(image,id){
  this.firestore.doc(`public/${id}`).set({
    img:image,
  });
 }

If anyone has a solution to efficiently synchronize the upload and retrieval of image URLs, please share. It would greatly help in optimizing the process.

Answer №1

putString() function is designed to be asynchronous, returning an UploadTask to keep track of the upload progress. Utilize the then() method, similar to a promise, to determine when the upload is successfully completed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can TypeScript restrict a callback parameter based on the type of another parameter using generics?

I am currently developing an event manager system. The main objective is to allow users to subscribe to events by providing an event type and a callback function. In my implementation, events are represented as classes, where AwesomeEventType in the exampl ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

Efficiently search and filter items across multiple tabs using a single search bar in the Ionic 2

I am currently working on implementing a single search bar that can filter lists in 2 different tabs within Ionic 2. The search bar is functional, and I have a method for filtering through objects. However, my goal is to allow users to select different tab ...

Why won't the sound play on the button with the picture?

I am currently working on a website project that requires buttons with pictures and sound. Despite my efforts, the sound feature is not functioning properly in Chrome and Firefox. I am still learning and would like to know how to toggle the sound on and of ...

Troubleshooting Angular HTTP: Issue with the HTTP request headers not updating

// assigning the httpclient protected _http: HttpClient = inject(HttpClient); // defining the options for the request const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/tcc' }), observe: 'resp ...

There seems to be an issue with calling this particular expression. The elements within the type 'string | ((searchTerm: string) => Promise<void>) | []' are not all callable

Here is my unique useResults custom hook: import { useEffect, useState } from 'react'; import yelp from '../api/yelp'; export default () => { const [results, setResults] = useState([]); const [errorMessage, setErrorMessage] = us ...

Adal TypeScript Document

Recently, I've been experimenting with the TypeScript version of adal.js. As part of my setup process, I'm referring to this link to install adal.ts. However, after executing the command: npm install adal-typescript --save a new "node_modules" ...

Enhance your coding experience with VScode's intellisense feature when working with TypeScript

declare type Item = { name: string; location: string; source: string; }; declare type CollectionOfItems = { [key: string]: Item; }; export const CollectionOfItems: CollectionOfItems = { ITEM_1: { name: 'Item 1', location: &ap ...

Using import statement is mandatory when loading ES Module in TS Node: server/src/index.ts

Attempting to kickstart a TypeScript Node project, I've gone ahead and added some essential dependencies (TypeScript, ESLint, Mongoose, and GraphQL). However, upon executing the command: ts-node-dev --respawn --transpile-only src/index.ts An error me ...

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

Creating a function in Typescript that accepts an array of strings and generates an output with the strings utilized as keys

I am working on a function that takes an array of strings and generates an object where the strings are used as keys with a value of true assigned to each. Here is the code snippet for that: return keys.reduce((result, key) => { result[key] = true ...

Is there any way I can verify the invocation of signOut in this Jest test case?

I am attempting to perform testing on my home page within a next app. However, I have encountered an issue with a button in the Home component that triggers a logout firebase function. Despite my attempts to mock this function and verify whether or not i ...

Stop certain sections of Typescript code from being compiled

In my scenario, I have two classes: class A and class B. Class B extends class A. The issue arises when we consider a method in both classes. Class A has a method that accepts AProperties enum as its first argument. However, class B has a similar method th ...

Develop a TypeScript project in React that incorporates a dynamic country flag component

Hi there! I've been diving into the world of using React with TypeScript recently, and I came across a package called "react country flag" that I wanted to use for displaying country logos. However, I'm running into issues trying to use it with T ...

Creating specific union types for a bespoke React hook

There are 4 objects with both similar and different keys. The union of these objects is used for database operations as follows -> type Objects = Food | Diary | Plan | Recipe ; A Custom Pagination Hook function usePaginate (key: string, options: Option ...

Struggling with TypeScript declaration files has been a challenge for me

I'm encountering an issue with using the trace function in my TypeScript code. The function has been declared in a .d.ts file as shown below: declare function trace(arg: string | number | boolean); declare function trace(arg: { id: number; name: strin ...

typescriptExtract generic type from TypedDocumentNode<MyType, unknown> using introspection

I am currently utilizing a library that allows me to retrieve the type from a returned variable within a function. const myVar = gql(somestring) // The library function is called gql type myVarType = typeof myVar // The resultant value of myVarType is Typ ...

Exploring the power of combining React, styled-components, and TypeScript: Creating a functional component that encapsulates a styled component

Struggling to create a wrapper for my styled component with proper types. Imagine having a styled component defined like this: const Button = styled.button<ButtonProps>` background-color: ${(props) => props.color}; `; Now the goal is to have a ...

Error encountered when attempting to export a TypeScript class from an AngularJS module

In my application using Angular and TypeScript, I have encountered a scenario where I want to inherit a class from one module into another file: generics.ts: module app.generics{ export class BaseClass{ someMethod(): void{ alert(" ...