Error in Console while Json is not being displayed on the Screen in React Native

Encountering an issue while attempting to display JSON data from mongodb on the screen of a React Native Application. The screen is visible but no data is showing up. Below is the error message along with the code snippet. This is a basic hello world application where I am trying to fetch JSON data from mongodb onto the screen. Unsure about the correct setup, although I have the screen displaying up to selecting a listing in Listings.js file. It seems like there is an issue with the network connection. Not sure if I need to proxy in package.json?

App.js

import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {Listings} from './src/Listings';

type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <View style={{flex: 1}}>
        <Text style={styles.welcome}>Air BNB Data Screen</Text>
        <View style={{flex: 1, borderWidth: 3, borderColor: 'blue'}}>
          <Listings></Listings>
        </View>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

src Listings.js

import React from 'react';
import {StyleSheet, View, FlatList, Text} from 'react-native';
import axios from 'axios';

export class Listings extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      show: true,
    };
  }

  componentDidMount = () => {
    const options = {
      headers: {'Content-Type': 'application/json'},
    };
    axios
      .get('http://localhost:8080/api/Listings/10006546', options)
      .then((response) => {
        this.setState({
          data: [],
        });
        console.log(data)

      })
      .catch((error) => {
        console.log(error);
      });
  };

  renderRow = ({item}) => {
    return (
      <View containerStyle={{ elevation: 1, borderRadius: 15 }}>
          <View row>
              <View flex={2}>
                  <Text h4>{item._id}</Text>
              </View>
          </View>
      </View>
    )
}
render() {

  return (

        <View style={styles.container}>
            <Text h3 style={{ marginLeft: 10 }}>Choose your Listing!</Text>
            <View>
                <FlatList
                    style={{ marginHorizontal: 10, marginTop: 10 }}
                    data={this.state.data}
                    renderItem={this.renderRow}
                    keyExtractor={(item, index) => item._id}
                />
            </View>
        </View>

    );
  }
}

const styles = StyleSheet.create({
  container: {
    fontSize: 12,
    textAlign: 'center',
    margin: 5,
  },
});

Error in console - Receiving the following error in the console.

Error: Network Error at createError (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\axios\lib\core\createError.js:16)
        at EventTarget.handleError (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\axios\lib\adapters\xhr.js:83)
        at EventTarget.dispatchEvent (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\event-target-shim\dist\event-target-shim.js:818)
        at EventTarget.setReadyState (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575)
        at EventTarget.__didCompleteResponse (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
        at C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
        at RCTDeviceEventEmitter.emit (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
        at MessageQueue.__callFunction (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
        at C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
        at MessageQueue.__guard (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373

)

Answer №1

Resolving this issue turned out to be quite straightforward. After some searching, I discovered a workaround by substituting localhost with 10.0.2.2. This successfully resolved the network error, but now I am encountering an error stating that 'data is not defined'.

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

Converting a JSON Response to a Pandas Dataframe

I am attempting to retrieve an API response from and convert it into a Pandas Dataframe. Specifically, my goal is to extract the 'Points' array and load it into the data frame. I have tried using json_normalize as suggested in other posts, but a ...

The HTTP GET request in Express.js is throwing a 500 internal server error

I have implemented a GET API call to retrieve all users from my Logins database. However, I keep encountering 500 errors when making the request. Below is the code snippet I am using: const http = axios.create({ baseURL: "http://localhost:8080/api ...

Here is a unique rewrite of the text: "Learn the process of toggling the tabindex for

Is there a way to dynamically change the tabindex of an element based on its visibility in the viewport? I am looking to either reset the current tabindex when entering a new section and assign new values to elements within that section, or disable and re- ...

JavaScript - The left dropdown menu stubbornly remains visible when clicked in white space, unlike the right dropdown which disappears as expected. Puzzled by this inconsistency

Whenever I click on the selection criteria box, a dropdown menu appears. Clicking on the white space or the data table button makes the drop-down menu disappear, which is good. However, when I perform the same action for 'choose data table,' the ...

Updating the quantity of items in the shopping cart with React JS: A step-by-step guide

How can I update the quantity of an item in an ecommerce cart when a button is clicked? Currently, I am creating a card with a specific quantity and would like to increase this amount by clicking on a button. ...

deleting the bottom three rows from a data grid

I currently have a table with two buttons that allow me to add and remove rows from it. Adding a row is simple as I receive 3 rows via ajax each time. Now, the challenge is removing the last three rows of the table by clicking on the remove button. Unles ...

Node.js Link Management: A Guide to Updating Links

For some time now, I've been attempting to update the tabs on my navigation bar (including the links) when a user logs in. The issue arises on the index page, where users can access it both when logged in and not logged in. In my navigation bar, all t ...

Leveraging ASP.NET MVC 5 to integrate an online document viewer from Office 365, seamlessly displaying Word documents within a sleek, compact window

We have been struggling to showcase a Word document (.docx) within an iframe on our website using the Office 365 service. The document is stored in One-Drive for business online and has been appropriately shared. After signing in, we obtained a link to the ...

In Angular, the ng-click directive that assigns the value of tab to $index does not seem to be functioning properly

I encountered an issue within my app <li ng-repeat="name in tabs track by $index" ng-class="{selected: tab==$index}" ng-click="tab = $index">{{name}}</li> After clicking on each item, the selected class remains enabled and switching to anothe ...

The function url_for is failing to interpret the variables I am passing to

My goal is to allow users to upload images that are then displayed to all users. The variable "Data" holds the file name (e.g., "files/dog.png"). However, when I try to set the newImg.src value as "{{url_for('static', filename = data )}}", it onl ...

Is there a way to transfer information from Postgresql to mongoDB using Java programming?

I am currently working on transferring data from a PostgreSQL database to MongoDB. I have managed to create a JSON string and store it in a MongoDB collection, but only the first entry is being stored. Below is my code snippet: public class JsonToBson { ...

Leverage the power of AJAX to fetch and display controller action results on the current

this is my code of the view I've set up a dropdown menu with options that have values like /ControllerName/ActionName. Upon clicking one of the dropdown values, it redirects me to another page with the selected ControllerName and ActionName. However ...

What causes useEffect to be triggered multiple times, even when it is dependent on another useEffect function that is being executed repeatedly?

I have a specific requirement that involves using two useEffect hooks. First useEffect is used to set the latitude and longitude in the state with an empty dependency array. useEffect(() => { navigator.geolocation.getCurrentPosition(geo = ...

An illustration of React's "component did mount" in JavaScript is shown in this example

As I embark on my journey with React, I find myself exploring code examples and stumbling upon an interesting discovery. You can find the link to the React tutorial here. Below is a snippet of code from the lifecycles section; componentDidMount() { this.t ...

Tips for extracting values from a PHP array using JavaScript

Assuming we have a PHP array named $decoded: $decoded = array( 'method' => 'getFile', 'number' => '12345' ); The data from this array will be passed to a JavaScript function called get(params). funct ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

Iterate through each row in a table to locate a particular control by its ID and retrieve its

Is there a way to write a jQuery function that can loop through table rows and find hidden field values based on a specific hidden control ID ("hdnIsEmpty") without affecting other hidden controls? I'm facing this challenge and need help with finding ...

Leverage Firebase cloud functions to transmit a POST request to a server that is not affiliated with

Is it feasible to utilize a firebase cloud function for sending a post request to a non-Google server? It appears that being on the blaze plan is necessary in order to communicate with non-google servers. Essentially, I aim to perform a POST action to an ...

Functionalities of HTML controls

I currently have a select element in my HTML code which looks like this: <select> <option id="US" value="US"> </option> <option id="Canada" value="Canada"> </option> </select> My requirements are twofold: ...

JavaScript reference problem when copying

Initially, I create a raw array by using the following initialization: $scope.rawUsers = angular.copy($scope.users); Subsequently, I make modifications to the data like so: function filterUsers(searchString, onlyMine) { $scope.users = []; _.find($scop ...