React Native app utilizing Expo can successfully import local databases in a web view, but encounters issues when attempting to do so on smartphones

I created a small learning app and imported data from a local database using the following code:

import { StatusBar } from 'expo-status-bar';
import { Platform, FlatList, StyleSheet, Text, View, TextInput, Button, SafeAreaView, ScrollView } from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { Icon } from 'react-native-elements'
import * as React from 'react';
import { ListItem, Avatar} from 'react-native-elements';
import { Header } from 'react-native-elements';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { List, Colors } from 'react-native-paper';
import Moment from 'moment'; 

const MyComponent = () => {
    const [expanded, setExpanded] = React.useState(true); 
}
const handlePress = () => setExpanded(!expanded); 

export default class Db extends React.Component {
    state = {
      data: [], 
    }

    
    componentWillMount() {    //load data from a remote endpoint (where to instantiate the network request)
      this.fetchData(); 
    }
    fetchData = async () => {
      const response = await fetch('http://localhost:3000/Ph'); 
      const json = await response.json(); 
      this.setState({data: json}); //js object notation
    }
    
    keyExtractor = (x, i) => i //extract item

    
  
    renderItem = ({ item }) => ( 

        
                        <List.Section> 
                        <List.Accordion 
                            
                            theme = {{colors: { primary: '#00A1DE'}}}
                            style= {{ backgruondColor: '#00A1DE' }}
                            titleStyle = {styles.titleContainer}
                             title = {item.Name}
                           
                            
                            left= { props => <List.Icon {...props} icon = "account"  /> }>
                                <List.Item 
                                
                                titleStyle={styles.textContainer}
                                title= {item.Geburtsdatum}  left= { props => <List.Icon {...props} icon = "cake-variant"  /> }></List.Item>
                                <List.Item 
                                 
                                titleStyle={styles.textContainer}
                                title={item.hobbies} left= { props => <List.Icon {...props} icon = "table-tennis"  /> }></List.Item>
                                  </List.Accordion>
                                </List.Section>
    )
      render() {
        return (
            <FlatList 
              keyExtractor={this.keyExtractor}
              data = {this.state.data}
              renderItem = { this.renderItem }
            />
        )
      }
     
  
  }

  const styles = StyleSheet.create({
    textContainer: {
      flex: 1,
      height: '90%', 
      width: '90%', 
    }, 
    titleContainer: {
        fontWeight: 'bold',
       
        
        
    }
    
  });

While this setup works perfectly in the Expo web view, I encountered an issue when trying to view it on my iPhone by scanning the QR Code. The data does not show up, only the footer and header with the bottom menu are displayed...

I also noticed a yellow warning due to my ComponentWillMount function. However, I'm unsure if this is causing the problem. Any insights on why it's not working on my iPhone even though it works fine on the Web View from Expo?

Answer №1

Update your IP address in place of localhost

1.) Open the command prompt (cmd)

2.) Enter the command ipconfig

3.) Look for the

IPv4 Address. . . . . . . . . . . : 192.168.**.**
section

4.) Copy the IP address and replace localhost with it

5.) Done!

Here's how you can find your IP:

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

For example, if your IPv4 address is 192.168.100.84, your fetch should look like this

await fetch('http://192.168.100.84:3000/Ph'); 

Your component code should resemble the following; note that a Function component is used:

import * as React from 'react';
import Constants from 'expo-constants';
import { StatusBar } from 'expo-status-bar';
import {
  Platform,
  FlatList,
  StyleSheet,
  Text,
  View,
  TextInput,
  Button,
  SafeAreaView,
  ScrollView,
} from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { Icon } from 'react-native-elements';
import { ListItem, Avatar } from 'react-native-elements';
import { Header } from 'react-native-elements';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { List, Colors } from 'react-native-paper';
import Moment from 'moment';

const BaseURL = '192.168.100.84'; // Your IPv4 address here

export default function App() {
  const [Data, setData] = React.useState([]);

  React.useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const response = await fetch(`http://${BaseURL}:3000/Ph`);
    const json = await response.json();
    setData(json);
  };

  const keyExtractor = (x, i) => i; //extract item

  const renderItem = ({ item }) => (
    <List.Section>
      <List.Accordion
        theme={{ colors: { primary: '#00A1DE' } }}
        style={{ backgruondColor: '#00A1DE' }}
        titleStyle={styles.titleContainer}
        title={item.Name}
        left={(props) => <List.Icon {...props} icon="account" />}>
        <List.Item
          titleStyle={styles.textContainer}
          title={item.Geburtsdatum}
          left={(props) => (
            <List.Icon {...props} icon="cake-variant" />
          )}></List.Item>
        <List.Item
          titleStyle={styles.textContainer}
          title={item.hobbies}
          left={(props) => (
            <List.Icon {...props} icon="table-tennis" />
          )}></List.Item>
      </List.Accordion>
    </List.Section>
  );

  return (
    <FlatList
      keyExtractor={keyExtractor}
      data={Data}
      renderItem={renderItem}
    />
  );
}

const styles = StyleSheet.create({
  textContainer: {
    flex: 1,
    height: '90%',
    width: '90%',
  },
  titleContainer: {
    fontWeight: 'bold',
  },
});

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

Persuading on the Server-Side

After reading through the Google-Caja wiki, I became intrigued by its capabilities. From what I understand, with Caja we can send a snippet of HTML (such as a ) to Google-Caja's server (cajoling service) for processing. The HTML is cajoled and the Jav ...

Connecting to multiple databases in SQL Server using Node.js

I am trying to establish a connection with SQL Server that houses multiple databases. Using the mysql library for nodejs, my goal is to connect to SQL Server and execute queries on various databases based on the given query template below. SELECT * FROM d ...

What is the best way to ensure that the scroll position on each page in shinydashboard remains unaffected by changes in the scroll position on other pages?

When navigating between pages A and B in my shinydashboard app, I noticed that the scroll position of one page affects the scroll position of the other. How do I make the scrolls independent? To illustrate my issue, I've included a stable shinydashbo ...

Having trouble with the functionality of a Chrome extension content-script JavaScript that is set to run at document_end

Currently, I am in the process of developing a Google Chrome extension that is designed to hide the "news" section located on the right-hand side of Facebook, along with the ads displayed on the right side. Additionally, the background color is meant to be ...

Guide to incorporating external CSS and JavaScript into an Angular 2 project with Express.js and Node.js

As a newcomer to Angular2 and NodeJs, I am eager to learn how to integrate external CSS and JS in an Angular2 and Nodejs express app. Specifically, I am looking to integrate a bootstrap admin theme into my Nodejs application. The screenshots below provide ...

Ways to boost memory capacity in nodejs

I've been attempting to increase the memory limit in node.js, and to do so I added an environment variable. You can see how I did it here Unfortunately, it doesn't seem to be working as expected. I even tried using capital letters with no succe ...

Choose the CSS class based on the content provided

Help needed with CSS issue. I want to target the <tr> element's class using Bootstrap classes like .success or .danger. In my Vue.js project, the status name in my object does not align with the .success or .danger classes, but I still need to ...

Encountering an error with type mismatch for style transform properties while using react-native-reanimated

Currently working with the following versions: "react-native": "0.59.10" "react-native-reanimated": "^1.3.0" using TypeScript Encountering a type error related to transform properties. const Example = () => { const { translationX, gestureHandler } = ...

Interactive feature on Google Maps information window allowing navigation to page's functions

Working on an Angular2 / Ionic 2 mobile App, I am utilizing the google maps JS API to display markers on a map. Upon clicking a marker, an information window pops up containing text and a button that triggers a function when clicked. If this function simpl ...

What is the proper way to combine two arrays containing objects together?

I am faced with the challenge of merging arrays and objects. Here is an example array I am working with: [ { name: "test", sub: { name: "asdf", sub: {} } }, { name: "models", sub: {} } ] ...

Error with font import causing hydration issue in NextJS

Font integration dilemma: import { Lexend } from 'next/font/google'; const lexend = Lexend({ subsets: ["latin"] }); Incorporating the font: const SplashPage = () => { ... return ( <html lang="en" className={lexend.cla ...

Completing the regex properly

When using my editor, I am able to paste a video URL which is then converted by regex into an embed code. The URL in the WYSIWYG-editor looks like this: Once converted, the output HTML appears as: <p>http://emedia.is.ed.ac.uk:8080/JW/wsconfig.xml& ...

Python responding to an Ajax request using jQuery

Currently, I am experimenting with integrating a pre-built inline editor from the following source: https://github.com/wbotelhos/inplace Regrettably, the available support documentation is lacking and my expertise in Javascript, jQuery, or Ajax is limited ...

Checking the validity of admin users with Passport JS

I'm currently working on a Node.js and Express application with EJS as the front end. One challenge I am facing is implementing a middleware function using Passport that needs to run before all create, edit, and delete routes. function isLoggedIn(re ...

How can I toggle button states within a v-for loop based on input changes in Vue.js?

Within the starting point of my code: https://plnkr.co/LdbVJCuy3oojfyOa2MS7 I am aiming to allow the 'Press' button to be active on each row when there is a change in the input field. To achieve this, I made an addition to the code with: :dis ...

The process of setting up a carousel for tables using jQuery

I can successfully implement jquery for an image carousel, but now I need to find a way to create a sliding table format. Any assistance on this matter would be greatly appreciated. Here is the code I currently have: <ul> <li><a style= ...

Display information based on the radio button chosen

I've set up a radio button with options for "no" and "yes", but neither is selected by default. Here's what I'm trying to achieve: If someone selects "no", nothing should happen. However, if they select "yes", then a message saying "hello w ...

Exploring AngularJS with Filtering for Advanced Search Results

Currently, I have a search box that successfully searches values in a table using my code. <tr ng-repeat="b in bugs | filter:searchText"> Now, I want to take it one step further by allowing users to search specific columns if they include a colon i ...

Transferring information through AJAX and fetching through PHP

Below is my current AJAX code setup: optionScope.data().stage = 'b'; $.ajax({ url: "functions/contact.php", type: "post", data: {'stage': optionScope.data().stage}, success: function(data, status) { ...

Converting data from Node.js 6.10 from hexadecimal to base64 and then to UTF-8

I have a code snippet that generates "data" containing a JSON object. My goal is to extract the HEX-value from the Buffer in the data, and then decode it from HEX to BASE64 to UTF8 in order to convert it into a string. Here is the code snippet: console.l ...