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

Ways to adjust the position of a DIV based on its index value

I'm currently working on a unique project that involves creating a triangular grid using HTML and CSS. The challenge I am facing is offsetting each triangle in the grid to the left by increasing amounts so they fit seamlessly next to one another. Righ ...

Vue-router: the browser tries to open a <router-link> element as if it were a local file

Having some trouble with Vue-router - when I click on a navigation link, the desired component briefly displays before the browser tries to open it as a file. For instance, clicking on the "Badger!" link results in the browser attempting to open a local f ...

An error occurred: TypeError - Unable to access the 'value' property of a null object during a value change

Example ImageCreating a dynamic form where rows and select box options are added dynamically using 'x' and 'i' increment values in two JavaScript functions. The code works fine when the option selected is 0.5, but throws an error Uncaug ...

Encountering an issue with resolving 'create-react-class'

I have some files with hobbies listed in Data.js. I am attempting to add these hobbies and display them in a list format within my App.js file. However, I keep encountering an error stating that the create-react-class module cannot be found. Does anyone k ...

Using ServiceWorker with React and Typescript

If you are working on a javascript-based React project, adding a Service Worker is simply a matter of updating serviceWorker.unregister() to serviceWorker.register() in index.jsx. Here is an example project structure: - src |- index.jsx |- serviceWo ...

Ways to prevent endless loops from occurring?

Here is the code for my component: const Inscriptions = () => { // getting state const { inscriptions, loading } = useSelector( state => state.user ); // flag const instances = Object.keys(inscriptions).length; // dispatch ...

Why is passing data:{} to a route essential for achieving the desired outcome?

Check out the Angular Material Documentation Site passing {} to the Homepage route: {path: '', component: HomePage, pathMatch: 'full', data: {}} I'm interested in knowing the significance of data: {}. Recent Discovery Closer ex ...

Using ES6, when utilizing array map in ReactJS, the function does not produce a return value

One challenge I'm facing involves mapping an array to find a specific string value. Unfortunately, despite my efforts, the map function is not returning anything as expected. class Application extends React.Component { constructor(){ super(); ...

Error: Unable to locate npm package

I am currently working on an Angular application that was created using Grunt and relies on Bower and NPM. Recently, I attempted to install an npm module locally. The installation resulted in the files being stored in the main application directory under ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

How should the directory be organized for the param with a prefix in Nuxt.js?

My route is set up as /en/rent-:productSlug How should I organize the directory for this route, considering that the parameter productSlug includes the prefix rent? ...

Can anyone figure out why this code is not functioning properly? It seems to be targeting the body element and all of

Currently, I am utilizing jqtouch to create a mobile website. In addition to this, I am incorporating a gallery image slider into the website. However, I have encountered an issue where the images do not display when placed between <div id="project_name ...

Access parent component's properties by clicking on child component

I'm uncertain if my current approach is the most effective solution to my issue, so I am open to alternative methods. My goal is to access the properties of the parent component when clicking on a child component (Image). Below is the code I have imp ...

Retrieving external response data within a nested $http request

Excuse me as I am new to working with AngularJS. I am trying to figure out how to properly handle a nested $http call in my code, $http({ method: 'GET', url: host1, params: { 'format': 'json', } }).then(function ...

Error in React Bootstrap: ReferenceError - 'openModal' is not defined

Whenever the button is clicked, my intention is for a modal to open. I have written the code for it, but I'm encountering errors that I can't seem to resolve. Here's the snippet of my code: import React from "react"; import { M ...

What is the best way to utilize an Angular service method from a controller?

As a newcomer to Angular, I have created an 'Employee Search' Service module. Let's take a look at the code: // Employee Search Service app.service('employeeSearchService', function($http, resourceServerAddress){ this.empList ...

Vanilla JavaScript: Enabling Video Autoplay within a Modal

Can anyone provide a solution in vanilla JavaScript to make a video autoplay within a popup modal? Is this even achievable? I have already included the autoplay element in the iframe (I believe it is standard in the embedded link from YouTube), but I stil ...

Replicate the functionality of a mouse scrolling event

I have incorporated Jack Moore's Wheelzoom jQuery plugin to zoom and drag an SVG image on my website. However, I also want to include manual zoom in and out buttons for the users. I am considering two options to achieve this - triggering a mouse whe ...

JavaScript codes within HTML elements may not be functional when using an AJAX loader to transition to the next page

I'm experiencing issues with an ajax loader in Wordpress. The theme I am using has an ajax loader button that is interfering with my inline script. Despite reading over 10 articles on the problem, I haven't been able to find a solution yet. Do ...

Interactive PDFs that launch a new browser tab rather than automatically downloading

I am facing an issue with my web API that is returning a JSReport as an encoded byte array. Despite multiple attempts to read the byte array, I keep encountering either a black screen or an error message indicating "failed to download PDF". Interestingly, ...