React Native listview fetch issue: troubleshoot in progress

Currently, I am attempting to retrieve information from a JSON file by utilizing the fetch method and then showcasing the data using a Listview React Native component. The data fetched is successfully stored in this.state.films, as evidenced by displaying the film's title with {this.state.films[0].title}. However, when trying to implement a Listview, all I get is "[]". What could be the issue? I am referring to the React Native documentation where I am merging two sections: "Networking" and "Using a list view", and using the provided JSON data. Any assistance would be greatly appreciated. Thank you!

Below is my code for index.windows.js

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  ListView
} from 'react-native';

class AwesomeProject extends Component {
   constructor(props) {
    super(props)
    this.state = { films: [] }
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
  }

  componentWillMount() {
    fetch('http://facebook.github.io/react-native/movies.json')
      .then((response) => {
        return response.json()
      })
      .then((movies) => {
        this.setState({ films: ds.cloneWithRows(movies.movie) })
      })
  }

  render() {
      return (
        <View style={{paddingTop: 22}}>
          <ListView
            dataSource={this.state.films}
            renderRow={(rowData) => <Text>{rowData.title}</Text>}
          />
        </View>
      );
  } 

}


AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

Answer №1

React Native provides a convenient solution called the FlatList, which simplifies working with lists compared to ListView. The FlatList can be implemented as shown below:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  FlatList
} from 'react-native';

class AwesomeProject extends Component {

  state = { 
    films: [] 
  }

  componentWillMount() {
    fetch('http://facebook.github.io/react-native/movies.json')
      .then(response => response.json())
      .then((films) => {
        this.setState({ films })
      })
  }

  render() {
      return (
        <View style={{paddingTop: 22}}>
          <FlatList
            data={this.state.films}
            renderItem={({item}) => <Text>{item.title}</Text>}
          />
        </View>
      );
    } 

}


AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

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

I need to loop through an array of ids and add a new mongodb document for any ids that are missing. What is the best way to ensure that they are saved permanently?

Currently, I am utilizing Node JS and MongoDB to manage a collection of documents containing IDs ranging from 1 to 5000. Nevertheless, there are certain IDs that are absent, and I would like each document to be assigned one unique ID. Below is the snippet ...

Utilize AjAx and the post method to transmit data to a servlet

function checkInputValue (value){ var input = value; $.ajax({ url:"ggs.erm.servlet.setup5.AjaxS", data:{ userInput :input}, success:function(){ alert("Success! Code executed successfully."); } }); } ...

The loading icon on Chrome continues to rotate while handling XMLHttpRequest requests

I'm currently developing a web app using AJAX with Comet/Long Polling to ensure real-time updates on the web page. I've noticed that in Chrome, the page is constantly loading (tab icon keeps spinning). Initially, I thought this was a normal beha ...

Error Message: "Unable to Locate Tracking Information" while running UPS RESTful Integration Testing API URL

Recently, I encountered an issue while trying to retrieve data from the UPS RESTful API using my correct track number and API key. The error message "TW0001, Tracking Information Not Found" appeared when I used the Integration Testing URI (https://wwwcie.u ...

Bootstrap 2.0.3: Accordion Collapse feature no longer functioning

Previously, my accordion functioned perfectly with Bootstrap 2.0.2, utilizing data-toggle="collapse" and data-parent="#selector". However, after upgrading to version 2.0.3, the accordion stopped working as expected. While it still opens and closes the des ...

Angular: The property '**' is not found on the type 'Object'

Not too long ago, I embarked on a new Angular project where my setup involves Angular (the front-end) communicating with a node.js server (the back-end), which in turn might make requests to an api server or a mongo database when necessary. The tricky par ...

Tips for saving data after reading lines in Node.js

I am working on a project where I need to read data from an external text file into my function. How can I efficiently store each line of the file as a separate variable? const fs = require("fs"); const readline = require("readline"); const firstVariable ...

Implementing CSS transitions across several elements simultaneously can enhance the user experience

There seems to be an issue with animating two elements simultaneously using max-height. The transition always occurs one after the other, with one element completing its transition before the other starts. setTimeout(function () { $(".b").css( ...

Interact with a shared array across multiple HTML pages using JavaScript

Currently, I am developing a web application that involves pushing values into an array through a JavaScript function on one HTML page and then accessing the same array from another JavaScript function on a different HTML page. Here is the code snippet I ...

The automation script for Playwright/Puppeteer is having trouble properly handling `async...await` in a `for..loop` on the `/signup` page

Currently, I am faced with the challenge of automating rate-limit requests using a playwright automation script. The issue arises when the script keeps attempting to sign up with the email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Dealing with SSE reconnection errors in Angular 8

Currently, as part of an Angular 8 project with Electron 6 and Ionic 4, we are in the evaluation phase of deciding whether to replace polling with either SSE (Server-sent events) or Web Sockets. My task involves researching SSE. To test SSE, I set up a sm ...

What is preventing me from opening this local html page without an IIS Server?

Currently immersed in a passion project that can be found at https://github.com/loganhenson/jsrpg This project has been a collaborative effort with a friend, utilizing Visual Studio Professional for development and testing it on my local IIS server. Init ...

The decoding of a String using WebUtility.HtmlDecode does not work

Utilizing the WebUtility.HtmlDecode method, I am trying to decode a string. Here is a snippet of the string: checkin=%7B%22id%22%3A%224f612730e4b071dd72e3749d%22%2C%22createdAt%22%3A1331767088%2C%22type%22%3A%22checkin%22%2C%22timeZone%22%3A%22America%5C% ...

Parsing JSON output from curl with JQ

Looking for help filtering a JSON file extracted with Curl using JQ on an Ubuntu shell. I want to specifically extract and print the Youtube video ID XEJLuJyxLDE using the jq command, but my current command is not providing the desired output. Any assist ...

Show the JSON response in a specific div element by using the @Ajax.beginForm function

My goal is to show an error message returned from the server using Ajax.beginform in MVC4. Although I am receiving the response and error message from the server, when I try to display the error in a div, it appears as shown below: {"success":false,"Other ...

How to process and handle a JSON response containing multiple objects using JavaScript

I received a JSON response that looks something like this. { returnCode: 'Success', info: null, result: { payload: '{ "BatchNo":"143123", "Supplier":"Automotive", "ItemNumber":"AP123", ...

Launch a Bootstrap modal window using Spring MVC backend

I am working with a Spring MVC controller and a bootstrap page. My goal is to display a confirmation window when submitting a form and sending some payload to a specific endpoint if certain conditions are not met: API: @PostMapping(value = "/pairs") ...

Kurento's WebRTC feature is currently experiencing difficulties with recording functionality

Currently, I am attempting to capture video using the Kurento Media Server with nodejs. Following the hello-world example provided here, I connected a recorderEndpoint to the webrtcEndpoint and successfully got everything up and running. However, on the se ...

The preventDefault function fails to work in Firefox

My input is called shop_cat_edit and I've included the following code. However, it seems to work fine in IE but doesn't work in FireFox. Can anyone help me figure out what's wrong? $('[name=shop_cat_edit]').on('click',fu ...

How can we effectively monitor and record deleted items on the user interface to ensure they are accurately stored on the server?

I am currently developing a system in which teachers can manage the enrollment of students in their classes. The user interface allows them to add or remove students, as well as update details such as the class name and room number. Right now, I am implem ...