DEV Community

Discussion on: How to get data from an MySQL database in React Native

Collapse
 
yannb9 profile image
Yann Bohbot • Edited

Hey Saulo,

First off thanks for the great tutorial!
Unfortunately im stuck at a point where im using my react native app.
So first off, i built the node js and express and mysql code as you mentioned as follows:
Note that I created mysql database on a digitalocean server and have all the accesses possible for the user

const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');

const connection = mysql.createConnection({
    host: '134.122.22.176',
    user: 'yannb_9',
    password: 'yannb_9',
    database: 'tiomanGrow'
});

// Starting our app.
const app = express();

connection.connect((err) => {
    if (err) {
        console.log('Connection error message: ' + err.message);
        return;
    }
    console.log('Connected!')
    // Creating a GET route that returns data from the 'users' table.
    app.get('/', function (req, res) {
        // Connecting to the database.
        // Executing the MySQL query (select all data from the 'users' table).
        connection.query('SELECT * FROM farmers', function (error, results, fields) {
            // If some error occurs, we throw an error.
            if (error) throw error;
            // Getting the 'response' from the database and sending it to our route. This is were the data is.
            res.send(results)
        });
    });
});

// Starting our server.
app.listen(3000, () => {

    console.log('Go to http://localhost:3000/farmers so you can see the data.');
});

no worries this is for testing so i don't care to share my mysql credentials.
So far when i run my route.js code and check my localhost:3000 i see the data i need. Great!

My issue is when i run the RN app.
this is my code:

 import React from "react";
 import { View, Text, StyleSheet, TextInput, TouchableOpacity } from "react-native";
 import { HeaderImg } from '../components/HeaderImg';
 import { Button } from '../components/Button';

export default class DB extends React.Component {
    state = {
        email: "",
        password: "",
        errorMessage: null
    };

    fetchData = async() => {
        fetch('http://134.122.22.176:3000/farmers')
        .then(response => response.json())
        .then(users => console.dir(users))
        .catch(error=> console.log(error))
    }


    render() {
        return (
        <View>
            <HeaderImg />

            <View style={styles.errorMessage}>
            {this.state.errorMessage && (
                <Text style={styles.error}>{this.state.errorMessage}</Text>
            )}
            </View>
            <Button 
            onPress={this.fetchData}
            />
        </View>
        );
    }
}



const styles = StyleSheet.create({

});

The error that i get is Network request failed. do you have any idea whatsoever that it could return this error to me?