Utilizing React Native to Query, Filter, and Save a Single Document Field Value from Firestore Database into a Variable/Constant

My current task involves setting up a Firebase Firestore Database in order to filter it based on a specific field value within a document. The collection I am working with is named "PRD" and consists of thousands of documents, each sharing the same set of fields. Among these fields is a GTIN Number (String) which uniquely identifies each item. When receiving this GTIN Number from a barcode scan (referred to as data), my goal is to retrieve the Medication Name (known as DSCRD and located in a different field within the documents) associated with that particular GTIN Number.

Despite my efforts, I have encountered challenges when attempting to fetch the required data from Firebase. So far, various retrieval methods have been tested without success. Currently, the code for data retrieval appears as follows:

import { dbh } from "../firebase/config"
import firestore from '@react-native-firebase/firestore'
    dbh.collection('PRD')
    .where('GTIN', '==', data)
    .get()
    .then(documentSnapshot => {

      console.log('MedData',documentSnapshot.data())    
    });

The main issue lies in filtering the correct medication using the provided GTIN from the barcode scanner, and then storing the corresponding description field value into a variable.

It's worth noting that Firebase has been correctly set up, as evidenced by successful write operations to collections and documents within the database.

Below is the database structure, showcasing the PRD Collection housing all the medications, each containing GTIN and DSCRD Fields:

Answer №1

Your current implementation has a slight issue where you are attempting to call documentSnapshot.data() after querying a collection, which is not the correct syntax for fetching multiple documents. To handle a list of documents returned by the query, you should iterate through them like this:

.then(querySnapshot => {
  querySnapshot.forEach(doc => {
    console.log('MedData', doc.data())  
  })  
});

If the GTIN field is expected to fetch only one unique document, then you can directly access the name of the Medication from that single document like so:

var medName
dbh.collection('PRD')
.where('GTIN', '==', data)
.get()
.then(querySnapshot => {
   querySnapshot.forEach(doc => {
      console.log('MedData', doc.data())  
      medName = doc.data().DSCRD
   })  
});

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

Steps to display text in a div upon clicking on an image

I am trying to create an image with two DIVs separated by a black line. The left DIV will contain 4 images, and I want the following functionality: When a user clicks on any of the buttons in the left DIV, a corresponding text should be revealed in the ri ...

What is the correct way to handle fetch timeouts in a React component?

Utilizing a JavaScript timeout, I am able to fetch Dogs from my API successfully. However, there are instances where the timeout fails to clear properly: import { useState, useEffect, useCallback } from 'react'; const DogsPage = () => { c ...

An individual in a chat App's UserList experiencing issues with incorrect CSS values. Utilizing Jquery and socketio to troubleshoot the problem

Currently, I am testing a new feature in a chat application that includes displaying a user list for those who have joined the chat. The challenge is to change the color of a specific user's name on the list when they get disconnected or leave the cha ...

Utilize the findIndex method to search for an element starting at a designated index

Below is a snippet of code that I have: private getNextFakeLinePosition(startPosition: number): number{ return this.models.findIndex(m => m.fakeObject); } This function is designed to return the index of the first element in the array that has ...

What is the most effective way to retrieve the children and ID of an item in the jQuery Nestable plugin following a drag-and-drop action,

I'm currently implementing the jQuery Nestable plugin to build a menu editor for a website. After users click on menu items and rearrange their positions, I need to retrieve the item's ID and its Children.   Challenge: I'm struggling with ...

Creating a PEG Grammar that can match either a space-separated or comma-separated list

I am currently working on creating a basic PEG (pegjs) grammar to analyze either a space separated list or a comma separated list of numbers. However, it seems like I am overlooking a crucial element in my implementation. Essentially, I aim to identify pat ...

Having trouble with my Express.js logout route not redirecting, how can I troubleshoot and resolve it?

The issue with the logout route not working persists even when attempting to use another route, as it fails to render or redirect to that specific route. However, the console.log("am clicked"); function works perfectly fine. const express = require('e ...

Error occurs when an arrow function is called before its function definition

console.log(addB(10, 15)); function addB(a, b) { return a + b; } console.log(addC(10, 15)); const addC = (a, b) => { return a + b; }; I attempted to convert a function into an arrow function and encountered the error "Cannot access 'addC&ap ...

Reactstrap: Is it necessary to enclose adjacent JSX elements within a wrapping tag?

While working on my React course project, I encountered an issue with my faux shopping website. The error message that keeps popping up is: Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...& ...

Unexpected behavior of ion-select: No rendering of selected value when applied to filtered data

I came across an unexpected issue with the dynamic data filtering feature of ion-select. In my application, users are required to choose three unique security questions during registration. I have an array of available questions: questions: Array<{isSe ...

I'm trying to display hidden forms on a webpage when a button is clicked using the DojoToolkit, but I'm having trouble figuring out what's going wrong with my code

Currently, I am trying to grasp the concepts of Dojotoolkit and my objective is to display a form when a button is clicked. Upon reviewing other examples, my code seems correct to me; however, there appears to be something crucial that I am overlooking but ...

When we modify the prototype of the parent object, where does the __proto__ point to?

Typically, when a new object is created using the "new" keyword, the __proto__ property of the newly created object points to the prototype property of the parent class. This can be verified with the following code: function myfunc(){}; myfunc.prototype.n ...

Reviewing user input for any inappropriate characters using jQuery's functionality

When a username is inputted into the input box, I want to make sure that only valid characters are accepted. The following code shows what I have so far; but what should I replace "SOMETHING" with in the regular expression? var numbers = new RegExp( ...

Having trouble getting my subarrays to push correctly into the parent array in ReactJS. What am I doing wrong

I am currently working on implementing the bubblesort algorithm using ReactJS. My state includes an array of 3 objects initially sorted in descending order by the 'num' property. I have a button on my interface that triggers the bubblesort functi ...

Tips for resizing user-uploaded images to fit the required dimensions outlined in the design draft using CSS or JavaScript

Hey everyone! I'm facing an issue but my English isn't great. I'll do my best to explain it thoroughly, and if anything is unclear, please feel free to let me know! So here's the problem: today there's a block for users to upload p ...

The alteration of arrays within React.js

I've been working on this function: setNotActiveWalletsList = () => { const { GetAccounts } = this.props; let shallowCopyOfWalletsArray = [...GetAccounts]; const notActive = shallowCopyOfWalletsArray.filter(user => user.active != ...

Difficulty navigating through pages on an iPad due to slow scrolling with JavaScript

My operation is executed within a scroll function, like this: Query(window).scroll(function(){ jQuery('.ScrollToTop').show(); // my operation. }); While my web page responds quickly to the operation, it seems slo ...

When there is an error or no matching HTTP method, Next.js API routes will provide a default response

Currently, I am diving into the world of API Routes in Next.js where each path is structured like this: import { NextApiRequest, NextApiResponse } from "next"; export default async (req: NextApiRequest, res: NextApiResponse) => { const { qu ...

An empty array is being returned by the Model.find() method after sorting

let query = Tour.find(JSON.parse(queryStr)); if (req.query.sort) { query = query.sort(req.query.sort);//a string 'ratings' } const tours = await query; res.status(200).json({ status: 'success', requestedAt: req.requestTime, ...

How to display a name in an iframe using React

When I retrieve the movie name in React, it appears correctly as {movie.name} / {movie.enname} ({years}) . However, when I try to display this name within an iframe window at https://example.com/movie/{movie.name}, it does not show up properly. Here is th ...