retrieve data asynchronously from a Firestore reference in Firebase

I am currently attempting to extract the name value from a promise retrieved from the Firebase Firestore database:

Just to provide some context, I have a collection of places that each contain information such as a name and a reference to an owner document, which only includes a name.

var names: any = [];
this.props.places.snapshot.docs.forEach((doc : any) => {
  const place = doc.data()
  place.ownerReference.get().then((snap : any) => {
    name.push(snap.data().name);
    console.log(names);
  })
});
console.log(names);

The first console log displays the expected data, however, the last one returns an empty object. I understand this is due to the asynchronous nature of promises. How can I ensure the desired value is properly assigned to this variable?

Answer №1

Gather all the assurances provided by each fetch() and store them in an array. Next, utilize Promise.all() to ensure they are completed before moving forward. Finally, navigate through the resulting snapshots in the callback function.

const assurances = []
this.props.locations.snapshot.docs.forEach((doc : any) => {
    const location = doc.data()
    assurances.push(location.ownerInfo.fetch())
})

Promise.all(assurances).then(snapshots => {
    const details = []
    snapshots.forEach(snapshot => {
        details.push(snapshot.data().details)
    })
    console.log(details);  // this displays the desired information
})

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

JavaScript Function for Shuffling an Array

Looking for advice on optimizing a function I'm developing. My goal is to: Double the frequency of numbers in an array Randomize the location of the values in the array. For instance: Imagine I have an array. [0,1,2,3] First, I need to dupl ...

What is the best method for displaying 3 items in each row from a mapped response in ReactJS using materialize css grids or react bootstrap grids?

I have been attempting to display three or four response items in a mapped out response on the same row, but I haven't had much success. While I have researched similar questions on Stack Overflow, I couldn't quite figure out how to apply those s ...

differentiating between user click and jquery's .click() method

There are <a href=".. tags on a page with an inline onclick attribute. If a user clicks one without being logged in, they will be prompted to log in. After logging in and the page refreshes, jQuery will trigger .click() on the <a> element to redir ...

What are some strategies for incorporating error handling into promise chains and design considerations for working with promises?

As I delve deeper into using promises, the implementation process has left me with uncertainties. Let's say we have a signup function that takes an email address, username, and password, and executes various asynchronous operations in sequence: Che ...

A guide to categorizing and tallying JSON data based on multiple keys within the past 30 days using JavaScript/jQuery

I am facing an issue while trying to display a chart and extract specific data from an array. My goal is to generate a chart based on three columns in a JSON array: Source, Campaign, and Date. The process involves grouping the data, counting it, and then ...

Swirling hues transforming into #000000 upon second attempt

My goal is to create a button that generates two random color codes. Initially, this button seems to work fine on the first click, but on the second click, both codes turn into #000000. Despite my attempts to troubleshoot the issue, I haven't been ab ...

How can API calls be efficiently made in React?

While working in React, I encountered a minor issue when calling the API because the ComponentWillMount method is deprecated. Here is what I did: class MyClass extends Component { constructor() { super(); this.state = { questionsAnswers: [ ...

The function fails to return a true value

Why is true never returned even when the given name exists in the array rows and the if(rows[i].userName == name) condition is met? function checkIfUserExists(name){ var isUserExists = false; OOTW.MYSQL.query('SELECT * FROM Time',functio ...

Working with JSON data in JavaScript is proving to be challenging

Here is a json encoded result: { "result":[ { "CODE":"STC\/R\/935", "WAY":"In", "DATE":"2016-02-19", "TYPE":"Re-Entry", "TKTP":"NA", "TIME":"2016-02-23 17: ...

When using jQuery and AJAX together, it seems that the POST method is returning

Currently experimenting with Cloud9. The current project involves creating an image gallery. On the initial page: There are a few pictures representing various "categories". Clicking on one of these will take you to the next page showcasing albums fro ...

Utilize Vue Fullcalendar's eventRender feature to seamlessly incorporate Vue components into your

I am utilizing the fullcalendar.io vue extension. I would like to customize event rendering in order to add actions, but the event callback only contains JavaScript elements. Is there a way to inject a vue component into it? <FullCalendar ref="fu ...

consolidating express routes in one consolidated file

I am attempting to consolidate routes into a single file using app.use app.js import express from 'express' import testRouter from 'testRouter' const app = express() app.use('/testRouter', testRouter) app.listen(3000) tes ...

Is there a reason why I can't load all Google charts on one webpage?

I am trying to use the Google Charts API to display various charts on my web page. However, I seem to be encountering an issue where the last chart is not loading correctly. Can someone point out what I might be missing in my code? I would greatly apprecia ...

Exploring the best practices for utilizing the error prop and CSS with the Input API in Material UI while utilizing context

When working with the MUI Input API props and CSS, I encountered an issue related to the {error} and its use. This is how my code looks: const [value, setValue] = useState<string>(cell.value); const [startAdornment, setStartAdornment] = useState< ...

Using React to update an existing array of objects with a new array containing objects of the same type

My issue involves an array in a class's state, referred to as A. A is populated with objects of type B through the function f in the constructor. Subsequently, I create a new array of objects of type B called C using f and new data. Upon setting the s ...

Incorporate a custom file input field and utilize jQuery to switch out the input type with a chosen image

.image-upload > input { display: none; } .upload-icon{ width: 100px; height: 97px; border: 2px solid #5642BE; border-style: dotted; border-radius: 18px; } .upload-icon img{ width: 60px; height: 60px; margin:19px; cursor: pointer; } <form> ...

Can you specify the nature of the clear dispatch action?

Below is the code snippet in question: useEffect(() => { dispatch(fetchMovieDetails(movieId!)); return () => dispatch(fetchMovieDetails(movieId!, "clear")); }, [dispatch, movieId]); The issue at hand is that this code snippet i ...

Find numbers below 100 in an array containing a mix of numbers and strings using Javascript

Looking for a way to create a function that will return a number under 100? Check out the code snippet below: const myArray = ['hello', 3, true, 18, 10,, 99 'ten', false] const isLessThan100 = (array) => { // Insert solution here ...

Utilizing Reactjs to efficiently transmit name and value to Material UI autocomplete

I am trying to customize the Material UI Autocomplete component. I need to pass name, value and onchange similarly to how it is done for TextField. Can someone please help me achieve this? My current code is not functioning as expected. < ...

Steps to properly specify the Express Error Type

When defining the variable err, I have opted to use any due to uncertainty about the correct type. I was anticipating an express.Error type, but none was found. What would be the appropriate way to assign a type to err? // Addressing Syntax Error in JSON ...