How to Set up a Database connection with ReactJS

The short answer to this question is: You shouldn’t use React to connect directly to your database. React is a front-end framework, it should only be responsible for the user interface. If you need a database connection, the right place for it is the back-end, that’s also where you’re going to fetch and process the data before you provide it to the presentation layer.

Now let me show you how to do that. In this example I’m using PosqgreSQL database and Node.js with Express on the server-side.

const express = require('express')
const app = express()
const { Pool, Client } = require('pg')
const pool = new Pool({
   user: 'postgres',
   host: 'localhost',
   database: 'db',
   password: 'pw',
   port: 5432,
})
 
app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});
 
app.get('/data', (req, res1) => {
      pool.query('SELECT id, description FROM products', (err, res) =>{
      if (err) {
	 console.log(err.stack)
      } else {
         res1.send(res.rows)
      }
   })
})
 
app.listen(3001);
 
module.exports = app;

This is the simplest possible example on how to connect and execute queries. I’ve used the node-postgres module to be able to interact with PostgreSQL, so don’t forget to install it on your NodeJS project.

Since you’re here because of React, I don’t want to get into details about NodeJS in this post, and as far as I know, lots of you aren’t even using NodeJS in the back-end. So all we need to know here is that our node application will provide data from the database via the following link: http://localhost:3001/data. Now let’s see how to use this link on the React project.

import React, { Component } from 'react';
import './App.css';
 
class App extends Component {
 
  constructor() {
      super();
      this.loadData();      
  }
 
  loadData(){
    this.state = { data: [] };
    fetch('http://localhost:3001/data') 
      .then(result=>result.json())
      .then(data=>this.setState({data}));
  }
 
  render() {
    return (
      <ul>
        {this.state.data.map(item=><li>{item.id} - {item.description}</li>)}
      </ul>
    );
  }
}
 
export default App;

In this example we have a very simple React component. Take a look at the loadData method, that’s where we are getting the data from the server. I’m using the fetch API to make the request, so all we have to do is provide the link and it will return the data for us. When it receives the response I’m storing the result in the local state so I can access it from the render method and present it as I like, in this case I’m showing the data as a list.

That’s it guys!! Hope you liked the tutorial, I tried to keep this post simple, so maybe it wasn’t as detailed as you expected, but if you have any doubts please don’t hesitate to ask, just leave a comment and I’ll do everything I can to help you.

Recommended for you

React.js Tutorial: Consuming JavaEE RESTful Web Services In this post I'm going to show how to consume Web Services with React.js, more specificalyJavaEE RESTful Web Services. I've already written a post showing how to create these web services with EJB 3, if you haven't seen it yet just click on this link for more details, but if you're already familiar ...
Reacjs Error: The `style` prop expects a mapping from style properties to values, not a string. For ... This error occurs when you try to pass regular CSS strings to the style attribute of an HTML element. In React, the styling is different, instead of an string the style attribute expects an object. So instead of doing this: text you should do this: var pStyle { fontSize: '12px'...
Tutorial: Integrating AngularJS with NodeJS Integrating AngularJS with NodeJS I know this tutorial may seem a little bit too basic for a lot of you, but these are two of the most popular javascript frameworks at the moment, as a result of that there are lots of people just getting started with NodeJS and AngularJS, and it's a very common ...
Compiling JSX ReactJS code with Browserify and Reactify This will be a very basic tutorial for those who are just getting to know React, by now you should have noticed that React uses JSX code, which is basically Javascript with some HTML elements. The problem here is that the browser cannot understand JSX, if you have already tried it you probably saw ...

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>