The React Native Firebase query is displaying in the console.log but is not appearing on my screen

Although the data is displaying correctly on console.log, it's not showing up on my screen. Below is a snapshot of the console log for reference.

https://i.sstatic.net/qE4mC.png

This is the code I'm using:

componentWillMount = () => {
this.getData();
}

getData(){
  const { currentUser } = firebase.auth();
    firebase
    .database()
    .ref(`/users/${currentUser.uid}/data/`)
    .orderByKey()
    .on('child_added', snap =>  {

      //Is this correct or does it need to be formatted a different way?
      snap.key, 
      snap.val().Weight 

      //note that the console logs below displays the data
      console.log(snap.key)
      console.log(snap.val().Weight)

    }) 
}

renderRow = () => {
  return (
    <View style={[styles.card, styles.cardBorderTop]}>
      <Text>
        {snap.key} //Is this the correct way to reference this value?
      </Text>
      <Text style={[styles.textRight]}>
        {snap.val().Weight} //Is this the correct way to reference this value?
      </Text>
    </View>
  )
}

  render() {
    return (
      <View style={[styles.container]}>
        <FlatList
          data={this.getData} //Is this the correct data reference?
          renderItem={this.renderRow} 
        />
      </View>
    );
  }
}

The current output on my screen looks like this. Ideally, the data should be displayed in a FlatList. https://i.sstatic.net/0qfsW.png

Any guidance or assistance would be highly appreciated.

Additionally, I have come to understand that storing dates as ISO-8601 format will aid in better sorting. This adjustment will be made once I resolve the issue with rendering query data on my screen.

UPDATE Upon reflection, I acknowledge that my question might lack clarity and apologize for any confusion caused. My objective is to determine the appropriate references needed to display query results containing the date key and the Weight child on my FlatList. Although I can successfully retrieve this data using snap.key and snap.val().Weight in the console, I believe there might be incorrect references preventing their display on the FlatList.

For a visual representation, here is an image of my Firebase database: https://i.sstatic.net/PkkTr.jpg

Answer №1

The current getData function does not have a return statement, so when the view calls getData(), it does not receive any data in return.

Simply adding a return statement will not solve the issue because the data is loaded asynchronously. In React, it is recommended to store the data in the component's state using setState() and then access it from there in the render method.

In practice:

componentWillMount = () => {
  this.setState({ data: [] });
  this.getData();
}

getData(){
  const { currentUser } = firebase.auth();
  firebase
    .database()
    .ref(`/users/${currentUser.uid}/data/`)
    .orderByKey()
    .on('child_added', snap =>  {
      var data = this.state.data;
      data.push({ key: snap.key, weight: snap.val().Weight });
      this.setState({ data: data });
    }) 
}

This code:

  • Initializes a data property in the component's state as an empty array.
  • Adds each new item to the data array as it arrives from the database.

With this setup, you can render the array of data like this:

renderRow = ({item}) => {
  return ( 
    <View style={[styles.card, styles.cardBorderTop]}> 
      <Text> 
        {item.key} 
      </Text> 
      <Text style={[styles.textRight]}>
        {item.Weight} 
      </Text>
    </View>
  )
}

render() {
  return (
    <View style={[styles.container]}>
      <FlatList
        data={this.state.data}
        renderItem={this.renderRow} 
      />
    </View>
  );
}

There may be syntax errors in the last part, especially with FlatList. For accurate information, refer to the documentation for FlatList here.

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

Implementing automatic value setting for Material UI slider - a complete guide

I am working on developing a slider that can automatically update its displayed value at regular intervals. Similar to the playback timeline feature found on platforms like Spotify, Soundcloud, or YouTube. However, I still want the slider to be interactive ...

Running zgrep using node.js

I'm looking to incorporate the zgrep command into my node.js app. Currently, I have successfully integrated the grep command as shown below: const grep = require('grep1'); grep(['greptext', './logs/file], function(err, stdou ...

Extracting information from a string with JSON in Javascript

Can you assist me? I have developed a web service that provides a clean string after clicking on the URL: { "PersonID": 125, "Title": "Security Officer", "Company": "TSA", "CellNum": "423-915-3224", "EmergencyPhone": "", "Email": " ...

The Minimax algorithm experiencing issues in Next.js

I recently wrote some code in Next.js, but unfortunately, it's not functioning as expected. Despite my best efforts and attempts at utilizing alpha beta pruning, the code still fails to work properly. The issue lies in the fact that it simply returns ...

Loading data into a database using JSON format with JavaScript

I need to extract data from a JSON String stored in a JavaScript variable and use it to generate an SQL script. How can I loop through the JSON string to produce an output like the following? INSERT INTO table VALUES ('$var1', '$var2', ...

Tips for resolving a flickering issue that occurs when switching to an input field with our default value / placeholder plugin

In the realm of web development, numerous plugins cater to the implementation of HTML5's placeholder attribute in older browsers. The plugin we have opted for can be found here. Unlike some other alternatives, this particular plugin, with a few modif ...

Building a table with Next.js

I need assistance in displaying users and their metadata in a table on my website. Here is the code snippet I have: const apiKey = process.env.CLERK_SECRET_KEY; if (!apiKey) { console.error('API_KEY not found in environment variables'); proc ...

Why is Joi validation triggering an error when dealing with a nested object? Could this issue be connected to the use of dot notation in the

I am facing an issue with my joi validation when trying to submit a form. The error message I receive is: STACK: Error: "author.surname" is not allowed at module.exports.citationJoi Upon reviewing my joiSchema, everything seems correct: const n ...

What sets npx apart from npm?

As someone who is new to React, I recently began exploring the platform and found that Facebook offers a convenient way to kickstart a project by providing a pre-made project. To install this starter project, all I have to do is run npx create-react-app m ...

Having trouble importing the hash-set module in TypeScript/SystemJS?

In the midst of developing an Aurelia project with TypeScript to generate JavaScript, I decided to incorporate another custom library called 'hash-set' (installed using jspm install npm:hash-set --save). However, I encountered difficulties in act ...

JavaScript list items experience unreliability once stored in the database

I am in the process of setting up an ajax endpoint on my server to create a new transaction object and add it to a block, which is then added to a local blockchain. The problem arises when I invoke my database function add_block, responsible for adding th ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

Acquiring data from a separate Redux slice and utilizing it as the default state in a distinct slice

In my application, I have two Redux slices called userSlice and cartSlice. My goal is to extract the specific value userName from the userSlice and use it as the initial value for a property named user in the cartSlice. Despite my efforts, I am encounterin ...

There was an issue with the Discord.js (v12) Giveaway Command that resulted in an error stating "Error: Cannot read property 'hasPermission' of undefined"

Hey everyone, I'm trying to develop my own Discord bot and I want to add a giveaway command to it. I found an example code online that I tried to implement, but unfortunately, it's not working as expected... const ms = require('ms'); c ...

Encountered error code 253 while trying to run npx react-native init on a Mac M1

An error is occurring when I run the following command: npx react-native init awesomeproject npm version: 6.14.15 node version: v14.17.6 npm ERR! code Z_DATA_ERROR npm ERR! errno -3 npm ERR! zlib: incorrect data check npm ERR! A full log of this run can ...

Exploring the potential of Apollo React Hooks through Jest and React Testing Library

I am working on a form that utilizes an Apollo mutation hook: import React from 'react' import { useFormik } from 'formik' import { useLoginMutation } from '../generated' const LoginContainer = () => { const [loginMutat ...

An error has occurred with TokBox: OT.Session is unable to connect because the session has already been declared as

I encountered a similar issue but I'm struggling to make sense of what's going on. I have created a .Net page that includes all the necessary TokBox methods for subscribing. The process involves launching a new window (video monitor for multiple ...

Providing the unique identification number for the title of the document

Seeking advice on the most efficient method for storing user preferences in a Firestore database. Let me illustrate with an example... Scenario 1 In my "users" Collection, I have documents with randomly generated names and 3 fields: user_uid: String ni ...

Unable to locate the MoreVert icon in Material UI interface

I am trying to incorporate the MoreVert icon into my application's header to display signout and settings options. I have added the MoreVert icon as shown below, and although the popup appears when clicking on the supposed location of the icon, I am u ...

I'm having trouble getting PHP/AJAX to return the expected XML data - it keeps

I have a JavaScript script that looks like this: function showItems(type) { var xmlhttp = new XMLHttpRequest(); //creating object var call = "getitems"; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState ...