I am trying to fetch data using React Native from my localhost.
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
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)
}
})
})
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.
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.
- https://www.youtube.com/watch?v=IuYo009yc8w
- https://www.youtube.com/watch?v=MY_DEKLQiOU&list=PLWrTy7mdWLT2GXLCZynIcGNu7006uHT1x&index=2
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.