The Flatlist in React Native seems to be displaying extra empty rows instead of the expected number

When executing the code below, it is displaying 3 empty rows instead of two rows with a color and end date. I intend to use 'Parent' as the primary key that was created by Firebase when the color and enddate were pushed using '.push'.

I have tried various approaches to fix this issue. Although I managed to display content by modifying 'renderItems' to return 'this.state.list', it resulted in 3 lines all containing the same data from the last array on the console log.

Your assistance in resolving this matter would be greatly appreciated.

The following sections include the code snippet, a snapshot of the Firebase database, and the console.log output. Please note that the Firebase 'goal' has been changed to 'color'.

import React, { Component } from 'react';
import { Text, FlatList, View, Image } from 'react-native';
import firebase from 'firebase';
import { Button, Card, CardSection } from '../common';
import styles from '../Styles';

class List extends Component {

  static navigationOptions = {
    title: 'List',
  }

  constructor(props) {
    super(props);

    this.state = {
      list: [],
    };
  }

componentDidMount() {
    const { currentUser } = firebase.auth();
    const Parent = firebase.database().ref(`/users/${currentUser.uid}/Profile`);

    Parent.on(('child_added'), snapshot => {
        this.setState({ list: [snapshot.key, snapshot.val().color, snapshot.val().enddate] });

    console.log(this.state.list);
    });
}

keyExtractor = (item, index) => index;

render() {
  return (
    <Card>
      <View style={{ flex: 1 }}>
        <FlatList
          data={this.state.list}
          keyExtractor={this.keyExtractor}
          extraData={this.state}
          renderItem={({ item }) => (
            <Text style={styles.listStyle}>
                { item.color }
                { item.enddate }
            </Text>
          )}
        />
      </View>

      <CardSection>
        <Button
          style={{
            flex: 1,
            flexDirection: 'row'
          }}

          onPress={() =>    this.props.navigation.navigate('NextPage', { name: 'user' })}
          title="Go to next page"
        >
          Go to next page
        </Button>
      </CardSection>
    </Card>
    );
  }
}

export { List };

Answer №1

Here is the optimal method for storing the list data:

componentDidMount() {
    const { loggedInUser } = firebase.auth();
    const ParentNode = firebase.database().ref(`/users/${loggedInUser.uid}/Profile`);

    ParentNode.on(('child_added'), snapshot => {
        const newChildData = {
           key: snapshot.key, 
           color: snapshot.val().color, 
           enddate: snapshot.val().enddate
        }
        this.setState((prevState) => ({ list: [...prevState.list, newChildData] }));

    console.log(this.state.list);
    });
}

Also include this keyExtractor function:

keyExtractor = (item, index) => item.key;

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

Combine two scope arrays in AngularJS

Is there a way to merge two arrays of scope in AngularJS within my controller so that I can display them in a single table? The merging would be based on a common field present in both arrays, similar to an SQL join operation where data from both tables ...

Differentiating a path element in SVG by dynamically adding color using d3 and react

I have a unique SVG icon: <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <circle cx="12" cy="12" r="12" /> <path class="svg-fill" d="M12,2A10,10,0,1,0,22, ...

Progressively updating elements one by one leads to updates

I am currently working on a webpage where one element ('.item--itemprice') updates its text through a function that I don't want to modify. My goal is to have another element ('.header--itemprice') update its text to match the firs ...

Month and year selection feature in ExtJS 4 catalog

I recently came across an interesting Fiddle that featured a Month and Year picker for apps. After finding this Fiddle here, I noticed that it was built using Extjs 5.0, and it worked perfectly. However, when attempting to switch it to version 4.2.1, the l ...

Modal for Firestore CRUD operations update()

Currently seeking assistance with a CRUD system that involves modal dialogues. I have successfully implemented adding and deleting functionalities, but I am encountering an issue with editing. Although I can retrieve the data for each record in its respect ...

Obtaining an Array through a direct input on the command line

I am having trouble incorporating raw command line arguments in my Node.js application. When I try with simple variables, everything works as expected (node example.js variable) However, when I pass an array as an argument, it does not work properly (n ...

Highlight all the written content within the text box

I'm struggling with a piece of code that is supposed to select all the text inside an input field: <input id="userName" class="form-control" type="text" name="enteredUserName" data-ng-show="vm.userNameDisplayed()" data-ng-model="vm.enteredUs ...

There appears to be an issue with Javascript's ability to handle JSON API requests

I'm currently working on a webpage that utilizes the openweathermap API to showcase the user's city and local temperature. Unfortunately, I'm encountering an issue where the JSON API is not being processed and nothing is happening. Despite r ...

Utilizing Dynamic Image Sources in Vue.js with the Help of APIs

Can someone help me figure out how to solve this issue? I have an API that returns a base64 image, and I want to load this image on my site. Any suggestions on where or how I should implement my function? This is the API call located in the methods: metho ...

Import the .obj file along with its original color information, without the need for the accompanying

I am facing a challenge with a .obj file that appears colored in software like MeshLab or Microsoft's 3D builder. However, there is no .mtl file linked to it. When I try to open it in ThreeJs using the most basic method, it shows up as grey. var load ...

Utilizing AngularJS: Transforming JSONP information into HTML

I'm relatively new to utilizing $http and fetching data from various websites. My main query is, how can I convert JSONP into HTML? Specifically, when using $http to request the Atari Wikipedia page, the content is displayed with and HTML elements. ...

Is there a workaround for the issue of the NodeJS Web Cryptography API require() being undefined in an unsecure origin (Heroku App)?

My goal is to implement the experimental Web cryptography API (SubtleCrypto) on my Node.js server hosted on Herokuapp. The aim is to encrypt data from a fetch request sent from gitpages to herokuapp, concealing sensitive information from the browser consol ...

Implement a one-second delay before nesting another animation

I'm currently utilizing a timeout function, but I am interested in using a delay instead. My goal is to have the second animation start when one second has passed from the beginning of the first animation, and it should be a linear animation. How can ...

Trouble with the navigation of the JavaScript image gallery: next and previous buttons are not

Is it possible to have multiple galleries on a single page with captions? I've been trying to incorporate this JavaScript code, but struggling to make the next/previous links function for both galleries. Since I'm new to JavaScript, any advice or ...

The CI environment encountered an error when building Expo, citing an issue with the babel-preset-expo configuration. Strangely, the builds run smoothly when

It's a classic case of "it works on my machine." I am currently working on developing two react-native apps, App A and App B. Both applications were initially bootstrapped using expo. Interestingly, when I run the command to build either app locally ...

Creating structured paths for retrieving data via HTTP GET requests

In my Laravel project, I have routes set up for requests in a traditional way: Route::get('edit/{user}', 'AdminUserController@getUser'); Route::post('delete', 'AdminUserController@deleteUser'); However, I am facing ...

transferring data from one HTML file to another using a loop with technologies such as HTML,

As a beginner in front end development, I am finding it a bit challenging at the moment. Here's what I have so far: 1 main HTML file (index.html) 1 JavaScript file (something.js) 2nd HTML file (something.html) Main HTML: <!DOCTYPE html> < ...

Mixing controllers with the same name in AngularJS from different modules can lead to

Recently, while working on an AngularJS web application with multiple sub-modules, I encountered a situation where two sub-modules had controllers with the same name due to them both having CRUD functionality. Here's a snippet of the code structure: ...

Trouble with the Sendhub API

I'm currently working with the sendhub API and encountering an error. The error message states that the specified format 'application/x-www-form-urlencoded' does not have a deserialization method available. It is recommended to double-check ...

Is there an equivalent of numpy.random.choice in JavaScript?

The Numpy.random.choice function is a handy tool that allows you to select a sample of integers based on a specific probability distribution: >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array([3, 3, 0]) Is there a similar feature in Java ...