0

I am trying to fetch data using React Native from my localhost.

  1. I have a database which I created using MySQL. The database is named test and the table is named users. It contains the following rows : picture

  2. I create the connections within the following script :

var express = require('express')
var app = express()

var mysql = require('mysql')
var bodyParser = require('body-parser')

app.use(bodyParser.json({type:'application/json'}))
app.use(bodyParser.urlencoded({extended:true}))

//create the connection
var con = mysql.createConnection({
    host : 'localhost',
    user:'root',
    password:'',
    database:'test'
})

//create a listen port number
var server = app.listen(4546, function(){
    var host = server.address().address
    var port = server.address().port
})

//connect to the server
con.connect(function(error){
    if(error) console.log(error)
    else console.log('Connected ! ')
})

app.get('/', function(req, res){
    con.query('SELECT * FROM users', function(error, rows, fields){
        if(error) console.log(error)
        else {
            //displaying the lines
            console.log(rows)
            res.send(rows)
        }

    })
})
  1. Now when I go to localhost:4546 I see the following : picture which are all the rows from the user's table as I asked in the script above.

  2. PROBLEM : When I try to fetch this data with the following React Native script (please see below), I do not get anything in between WELCOME and Bye Bye.

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

export default class ButtonBasics extends Component {

  state = {
    data:[]
  }

  componentWillMount(){
    this.fetchData()
  }

  fetchData = async() => {
    const response = await fetch('https://192.168.1.14:4546/')
    const json = await response.json();
    this.setState({data: json.results})
  }

  render() {
    return (
      <View >
          <Text>WELCOME !</Text>
          <FlatList
            data={this.state.data}
            keyExtractor={(x, i) => i}
            renderItem={({item}) => <Text>{item.FirstName}</Text>}
          />
          <Text>Bye Bye !</Text>

      </View>
    );
  }
}

I followed the following tutorials and did everything correctly but it still does not work.

ADDITIONAL INFO :

  fetchData = async() => {
    try{
    const response = await fetch('https://192.168.1.14:4546/')
    const json = await response.json();
    this.setState({data: json})
    console.log(data)
    } catch(e){
      console.log(e);
    }
  }
  

This outputs the following error : error

This is the output I get on my iphone (not running it on an emulator) : iphone screen

I am new at this so any tips would be helpful :)

SOLUTION : I changed https to http when using fetch and it works.

ricola
  • 31
  • 1
  • 10
  • did you try to fetch `fetch('http://localhost:4546/')`? – iamhuynq Apr 01 '20 at 07:40
  • put your fetch statement in a `try .. catch` block and tell us what error it shows. Are you running this on an emulator? – LonelyCpp Apr 01 '20 at 07:41
  • console.log your data state or json.results and check what it returns – yesIamFaded Apr 01 '20 at 07:43
  • @iamhuynq Yes I tried with localhost:4546 as well. – ricola Apr 01 '20 at 07:46
  • I checked out above YT video, in his case there's `result` key present in response but that's not available in your API response, try this `this.setState({data: json})` just in case – randomkrishna Apr 01 '20 at 07:49
  • @yesIamFaded when I console.log the data state it is empty and I receive the following warning : Unhandled promise rejection: TypeError: Network request failed]. Do you have an idea what this means ? – ricola Apr 01 '20 at 08:03
  • @randomkrishna Yes I modified this but I still get an empty array – ricola Apr 01 '20 at 08:04
  • @LonelyCpp No I am running it on my iphone. I get the following error with my try catch block : Network request failed. I edited my question (Additional info part) so you can have a look at the total error if needed – ricola Apr 01 '20 at 08:08

3 Answers3

0

Ok so your Array is empty and you get a Promise rejection so try this maybe:

  fetchData = async() => {
    const response = await fetch('https://192.168.1.14:4546/')
    .then(res => res.json())
    .then(data => { 
     this.setState({data: data})
     console.log(data) // just a check for yourself
     }   
    .catch(err => console.log(err))  
  }
yesIamFaded
  • 1,970
  • 2
  • 20
  • 45
  • I tried but it still gave me the same Network request failed error as shown in the ADDITIONAL INFO part of my question. – ricola Apr 01 '20 at 08:26
0

I see you are using react-native fetch with HTTPS, I will suggest you to use http instead of https during development, because react-native will not allow you to use self-signed cert(I don't see your code with cert, so you can't use HTTPS also) without going through a long, tedious of configuration. Your fetch will work successfully, if it is http://localhost:$someport.

Easiest way: Change your https to http

Harder way: If you insist on using it, please check out how to fetch with self issued cert.

It is a common problem: React-native fetch() from https server with self-signed certificate

Hope it helps.

cYee
  • 1,915
  • 1
  • 16
  • 24
0

Can you try to log the response ?

const { data: response } = await fetch('https://192.168.1.14:4546/')

maybe you get the data like this.

  • I tried your solution as well as an alternative but it did not seem to work. The problem was that I was using https and needed to use http – ricola Apr 01 '20 at 08:32