Steps for referencing an autogenerated id in a Firestore collection

I need assistance updating a 'progress' field in a document with an autogenerated ID (using Firestore) every time the progress button is clicked. https://i.stack.imgur.com/hZieN.png

Despite my attempts, nothing seems to work. Here is the method I have been trying:

useEffect(() => {
    var user = firebase.auth().currentUser;
    var email = user.email;
    var documentID = database.collection("ChosenChallenge").doc().id;

    database
    .collection("Users")
    .doc(email)
    .collection("ChosenChallenge")
    .doc(documentID)
    .update({
        Progress: percentRange
  })
  .then(() => {
    console.log('added!');
  });
    }, )

and here is the corresponding class:

import React, { useState, useEffect } from "react";
import './newprogressbar.css';
import { firebaseAppAuth, database } from "../firebase";
import firebase from "firebase/app";

export const ProgressBarContainer = (props) => {

let [percentRange, setProgress] = useState(0);

const handleUpdate = () => {
    setProgress(percentRange < 99 ? percentRange + 7.14285714 : 100);
    props.onChange(percentRange + 7.14285714);
}

const Range = (props) => {
    return (
        <div className="range" style={{width: `${props.percentRange}%`}}/>
    );
};

const ProgressBar = (props) => {
    return (
        <div className="progress-bar">
            <Range percentRange={props.percentRange}/>
        </div>
    );
};

useEffect(() => {
    var user = firebase.auth().currentUser;
    var email = user.email;
    var documentID = database.collection("ChosenChallenge").doc().id;

    database
    .collection("Users")
    .doc(email)
    .collection("ChosenChallenge")
    .doc(documentID)
    .update({
        Progress: percentRange
  })
  .then(() => {
    console.log('added!');
  });
    }, )

    return (
        <div id="progresscontainer">
            <ProgressBar percentRange={percentRange} />
            <button id="updatepic" onClick={handleUpdate}>Daily Update</button>
        </div>
    );
};

If anyone could offer some guidance, it would be greatly appreciated!

Answer №1

When you call <code>database.collection("ChosenChallenge").doc().id
, it generates a unique document ID every time. This means that the method does not have any pre-existing knowledge of which specific document you are targeting.

If you intend to update a document, you will need to know its existing ID. There is no way around this requirement. If you lack knowledge of the ID, you will need to conduct a query within the collection to locate the document ID based on certain criteria or information related to the document's content.

In cases where you are unaware of both the document ID and do not possess any filtering information to run a query, you may encounter difficulties. It might be necessary to reassess how Firestore is being utilized within your application in such scenarios.

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

Having trouble with NPM Moment.js in React: Why is moment__WEBPACK_IMPORTED_MODULE_2__format not functioning properly?

scenario, After resolving my current issue using dateFns (date-fns.org), I am interested in integrating Momentjs into the project as well. The task at hand involves converting data to a string format within an app built with create-react-app. However, wh ...

Why is 'this.contains' not recognized as a function when I invoke it within another function?

While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could thi ...

Tips for concealing a div when the mouse is moved off it?

My goal is to create a simple hover effect where hovering over an image within a view filled with images displays an additional div. This part works as expected. However, I'm facing issues when trying to hide the same div when the user moves out of t ...

Looking for a JavaScript code to create a text link that says "submit"?

Here is the code I have, where I want to utilize a hyperlink to submit my form: <form name="form_signup" id="form_signup" method="post" action="/" enctype="multipart/form-data"> ... <input type="submit" value="Go to Step 2" name="completed" /> ...

I am currently working on developing an HTML and JavaScript audio player that can play audio at specific scheduled times

Looking to create a custom HTML/JavaScript audio player that adjusts playback based on the time of day. For instance, if it's 1:00 pm, the file will start playing from 0:00 minutes; and if it's 1:01 pm, the file will begin playing from 1:00 minut ...

Maximizing the efficiency of a personalized hook that facilitates data sharing in React

I have developed a unique Custom Hook that looks like the following: import { useEffect, useState } from 'react'; import axios from 'axios'; const myCustomHook = () => { const [countries, setCountries] = useState([]); const [i ...

Cloning a repository does not support Typescript compilation

After creating an Angular2 component, I wanted to share the code with my colleagues. Therefore, I uploaded the code to Github, cloned the repository, ran npm install, and then npm run tsc. However, I encountered the following errors: error TS2318: Cannot ...

Encountered an error while attempting to execute the command npx create react app: spawn UNKNOWN error occurred

After attempting to execute a basic npx create-react-app, an unexpected error occurred: D:\>npx create-react-app abc npx: installed 67 in 4.255s Creating a new React app in D:\abc. Installing packages. This might take a couple of minutes. In ...

If Gulp is running continuously, what output will I receive?

After reading a helpful post on StackOverflow about gulp tasks (viewable here), I came to the conclusion that it's not advisable to omit returning anything in a gulp task. For proper synchronization of asynchronous tasks, the caller should wait. Pres ...

The text loader feature in THREE.js is failing to load

My first attempt at coding THREE.js resulted in a black screen when I tried to load the Text loader. Can someone help me resolve this issue? I kept getting the following error even after multiple attempts: three.module.js:38595 GET 404 (Not Found) ...

Utilize ZLIB and Node.js to create a compressed zip archive of a folder's contents

I need to compress all the files in a directory into a single ZIP file. Currently, I am using this code snippet: var fs = require('fs'); var tar = require('tar'); var zlib = require('zlib'); var path = require('path&apo ...

Tips for sending a JavaScript object from PHP to AJAX

I've been racking my brain for hours, scouring through countless articles, but I'm still unable to crack this puzzle. Here's the situation: I'm currently tinkering with Chrome extensions and I need to make a server call that will fetch ...

Unable to retrieve link text following readFile function. Selector functions properly in Chrome console

My goal is to extract hyperlink text. Using the google chrome console with my selector, I am able to retrieve a list of 15 link texts as desired. However, when I execute my code with the same selector, the el.text returns undefined in console.log while th ...

Convert a Node.js module from synchronous to asynchronous functionality

I recently developed a Node.js module that is designed to handle Handlebars templates. It reads a directory of these templates, compiles them, and then exports an object containing the templates with their names as keys: 'use strict'; var fs ...

Nuxt's axios is encountering difficulties in managing the server's response

Having just started working with Nuxt.js, I encountered an unusual issue. There is an endpoint in my backend API that allows users to reset their password by sending a token along with a new password. Although the request is being sent correctly and the s ...

Ideas for displaying or hiding columns, organizing rows, and keeping headers fixed in a vast data table using jQuery

My data table is massive, filled with an abundance of information. Firstly, I am looking to implement show/hide columns functionality. However, as the number of columns exceeds 10-12, the performance significantly decreases. To address this issue, I have ...

React components featuring Material UI icons

I'm in need of assistance. I am looking for the Material UI icons, but I can't seem to find any information on how to obtain them. https://i.stack.imgur.com/FAUc7.jpg ...

What methods can be used to continuously send data to another web page within my website using XMLHttpRequest()?

As I delve into working with node.js and express.js, my primary goal is to efficiently tackle a specific issue. One of the pages on my website is tasked with receiving location data in latitude var lat and longitude var long. The challenge at hand is to c ...

Monitor for the specific parameter in the incoming GET request

My application is using the POST method to submit jobs remotely. After submitting a job, I receive a unique job ID from the POST request that allows me to check the status of the job using a GET request. $http.get('http://localhost:8090/jobs/'+i ...

Is there a discrepancy in the value between data and computed properties in Vue components?

Upon reviewing my code, I have noticed that the value shown in the data of the component does not match the desired value. The code snippet is provided below: View.component('xxx-item',{ props:['item'], template:`xxxx`, computed: ...