Creating a React table with material UI PART 1

This will be a tutorial in how to create a table in react with node js to help us to persist in the database

What we are going to do

React table

In these tutorials we are going to set up a React table with material UI doing a CRUD(Create, Read, Update and Delete) functionalities. Well for being a long article I will divide into two parts: PART 1 first one we will be setting up our server and database using node js and express a node framework, PART 2 will be our react app with material UI.

So if you are like me and want to see the final project first take a look Demo

We are going to use node js, so if you don't have, I recommend you to install it Node

Our project will have 2 files server.js and main.js, the former will take care of database connections, routes, while the latter will be the database functions, like select, insert, update, and delete.

Initialize the project and create a server.js file

npm -y init

touch server.js

we will install express, dotenv, helmet, body-parser, cors, morgan, knex. Express is a framework, will help us to handle requisitions and also to create routes with its respective action Dotenv will take care of our environment variables, this means, not having hard-coded connection variables in the code the others packages are explained in the code

Npm Packages we are going to use

npm install express dotenv helmet body-parser cors morgan knex

Now let's go to server.js and paste

Server.js

const express = require('express')

// use process.env variables to keep private variables,
// be sure to ignore the .env file in github
require('dotenv').config()

// Express Middleware
const helmet = require('helmet') // creates headers that protect from attacks (security)
const bodyParser = require('body-parser') // turns response into usable format
const cors = require('cors')  // allows/disallows cross-site communication
const morgan = require('morgan') // logs requests

// db Connection w/ Heroku
// const db = require('knex')({
//   client: 'pg',
//   connection: {
//     connectionString: process.env.DATABASE_URL,
//     ssl: true,
//   },
//   debug: true
// });

// db Connection w/ localhost
var db = require('knex')({
  client: 'pg',
  connection: {
    host : process.env.HOST,
    user : process.env.USER,
    password : process.env.PASSWORD,
    database : process.env.DATABASE
  }
});

// Controllers - aka, the db queries
const main = require('./controllers/main')

// App
const app = express()

// App Middleware
const whitelist = ['https://raptor-invoice.netlify.app']
const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}
app.use(helmet())
app.use(cors(corsOptions))
app.use(bodyParser.json())
app.use(morgan('combined')) // use 'tiny' or 'combined'

// App Routes - Auth
app.get('/', (req, res) => res.send('hello world'))
app.get('/users', (req, res) => main.getTableData(req, res, db))
app.post('/users', (req, res) => main.postTableData(req, res, db))
app.put('/users/:id', (req, res) => main.putTableData(req, res, db))
app.delete('/users/:id', (req, res) => main.deleteTableData(req, res, db))

// App Server Connection
app.listen(process.env.PORT || 3000, () => {
  console.log(`app is running on port ${process.env.PORT || 3000}`)
})

After this we will create a folder called controllers and inside a file named main.js This file will be responsible by our database functions like CRUD(create, read, update and delete)

Main.js

const getTableData = (req, res, db) => {
  db.select('*').from('invoice')
    .then(items => {
      if(items.length){
        res.json(items)
      } else {
        res.json({dataExists: 'false'})
      }
    })
    .catch(err => res.status(400).json({dbError: 'db error'}))
}

const postTableData = (req, res, db) => {
  const { name, description, due_date, value, company, bank, paid_date, status } = req.body
  const added = new Date()
  db('invoice').insert({name, description, due_date, value, company, bank, paid_date, status})
    .returning('*')
    .then(item => {
      res.json(item)
    })
    .catch(err => res.status(400).json({dbError: 'db error'}))
}

const putTableData = (req, res, db) => {
  const { id, name, description, due_date, value, company, bank, paid_date, status } = req.body
  db('invoice').where({id}).update({name, description, due_date, value, company, bank, paid_date, status})
    .returning('*')
    .then(item => {
      res.json(item)
    })
    .catch(err => res.status(400).json({dbError: 'db error'}))
}

const deleteTableData = (req, res, db) => {
  const  id  = req.params.id
  db('invoice').where({id}).del()
    .then(() => {
      res.json({delete: 'true'})
    })
    .catch(err => res.status(400).json({dbError: 'db error'}))
}

module.exports = {
  getTableData,
  postTableData,
  putTableData,
  deleteTableData
}

also we will create a .env file on the root folder, here we will put our database configuration to use on heroku.

.env

PORT=
DATABASE=
USER=
PASSWORD=

For deloyment purposes we will use heroku, well the step to deploy is simple you can use heroku login on your terminal or push your code to github and just import. Once this is done go to resources tab, find more add-ons and create a heroku postgres, then you can just open on the link and get the variables, once you got it go to settings tab and reveal config vars and add one by one following KEY VALUE

EX: DATABASE g6rk9vugenf29v

Then your app should run normally, if doesn't, try to restart.

References:
Material table

Comments