How to get data from an MySQL database in React Native
Tags: sql, reactnative, node, javascript
Published: 2019-04-26 05:52:35

---
title: How to get data from an MySQL database in React Native
published: true
description: We'll be using NodeJS with Express to get some values in a local MySQL database easely.
tags: sql, react-native, nodejs, javascript
---
<h3>DISCLAIMER</h3>
<b>This article is pretty outdated.</b>
I wrote it a long time ago and I didn't knew NodeJS that well back then :)

React Native is a wonderful tool that I've been using to develop my startup's app, <a href="http://instagram.com/allugo_app">AlluGo</a>! Sometimes I would find myself struggling to do something as simple as getting data from a local MySQL database. So I decided to write this article to help anyone struggling with the same problem. Allons-y! 

<i>(By the way, I wrote this article in PT-BR <a href="https://www.linkedin.com/pulse/react-native-como-pegar-dados-do-banco-de-mysql-rest-penha-simplicio/">here</a> in case you guys are fellow brazilians)</i>

<b><u>Step[0]: Importing packages.</u></b>

First of all, on your command prompt <i>(yes I use windows plz dont kill me)</i>, go to your React Native project's folder, and use the following commands:

```js
npm install express

npm install body-parser

npm install mysql
```
That might take a little while, but that's how it goes. And don't worry, I'll explain what each of these packages do later on.

<b><u>Step[1]: Create your MySQL database.</b></u>

I mean, you probably did that already... I use <a href="http://www.wampserver.com/en/download-wampserver-64bits/">Wamp Server</a> to handle my local MySQL databases, just in case you need it.

<b><u>Step[2]: Routes.js.</u></b>

In your <b>React Native project</b> <i>(you can place it anywhere you want tho)</i>, create a file named <b>‘routes.js’</b>. This will be our server <b>(NodeJS)</b>, which we'll use to get data from the database. 

Yes, that's right. You're creating a <i>(simple)</i> NodeJS server! You can do a <b>full CRUD</b> if you want <i>but that's not the point of this article! :p</i>
Here's my files:

<img src="https://media.licdn.com/dms/image/C5612AQEqEapDLgB84A/article-inline_image-shrink_1000_1488/0?e=1561593600&v=beta&t=XtGwGajJkmjGIuYOW4c0QTagpBE9DTH_QLD09U9OKGA"/>

<b><u>Step[3]: Database connection.</u></b>

Now things may get a little tricky, but <b>don't worry</b>. First, I'll show you the code then I'll explain what everything's doing. Check this out:

```js
// This is the routes.js file!
 
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');

const connection = mysql.createPool({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});
```

Ok. Beautiful, right? Let's go step by step. The first three lines are simply <b>imports</b>. 

- On the first line, we're importing <a href="https://expressjs.com/pt-br/">Express</a>. It's a Node framework, which will create our server routes. He's great for creating APIs and stuff.

- On the second line, we're importing <a href="https://www.npmjs.com/package/body-parser">Body Parser</a>. It will help us getting data from our request's body.

- From the third line on, we're importing the MySQL module and creating a connection with our database. Once you do that, just fill it with your database's data (no pun intended). Follow this example:
```js
const connection = mysql.createPool({
  host     : 'localhost', // Your connection adress (localhost).
  user     : 'root',     // Your database's username.
  password : '',        // Your database's password.
  database : 'my_db'   // Your database's name.
});
```

<b><u>Step[4]: Getting data from a table.</b></u>

Ok, now this may get a little tricky <i>(I hope not)</i>. Again, I'll show the code and then explain it:

```js
// We're still in routes.js! Right below everything else.

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

// Creating a GET route that returns data from the 'users' table.
app.get('/users', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {
    
    // Executing the MySQL query (select all data from the 'users' table).
    connection.query('SELECT * FROM users', 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/users so you can see the data.');
});

```

- First of all, we <b>start our Express app</b>. 
- Then, we create a <b>GET route</b> named 'users', and that route will execute a query that will get all data from the 'users' table for us. 
- <i>SIDE NOTE: The route and table name <b>don't</b> need to be equal!</i>
- After that, we <b>start our server</b> on the 3000 port.

<b><u>Step[5]: Running everything.</b></u>

Ok, cool. Now, how do we run our server? To do that, <b>you don't need to run your React Native app yet</b>. 

- <b>Open</b> your Command Prompt, <b>navigate</b> to your 'routes.js' and <b>execute</b> it. To do that, use this command: 
`node routes.js`

As you can see, there's a little message on your CMD like this: `Go to http://localhost:3000/users so you can see the data`.
Now, open your browser and go there. As you can see, <b>IT'S WORKING!!11!!</b> <i>(probably)</i>

Now, how do we get that data on our <b>React Native App</b>? 
 - That's simple, we use the `fetch` function. 
 - To do that, instead of using 'localhost:3000', you'll have to <b>directly insert your PC's ip adress</b>. If you use 'localhost', you're acessing your <b>smartphone/emulator's localhost</b>. And that's not what we want. 
Follow this example:

```js
test(){
    fetch('http://yourPCip:3000/users')
      .then(response => response.json())
      .then(users => console.warn(users))
  }
```

All the data will be stored on the `users` variable. I added that function to a `onPress` event from a button. And as you can see, <b>there's the data</b>: 
<img src="https://media.licdn.com/dms/image/C5612AQHwTa7lU49Q0Q/article-inline_image-shrink_1500_2232/0?e=1561593600&v=beta&t=6u2vXWhDuuBsFKgOhmB-WhHA9ZKI2egwPyfEuv_qdoI"/>

Go ahead and do whatever you want with that data! I hope everything worked out and I didn't confuse you... <b>If something went wrong</b> or you have any questions/etc, feel free to comment! This is my first ever post on dev.to :)