Building a Dynamic Web Application with React and Oracle: CRUD Operations Made Easy

 

Introduction:
Welcome to our blog post where we will guide you through building a dynamic web application using React.js as the frontend framework and Oracle as the backend database. We'll cover the essential CRUD (Create, Read, Update, Delete) operations, which are the backbone of most data-driven applications. By combining the power of React's user interface with Oracle's robust data management capabilities, we'll create a seamless user experience.

Prerequisites:
Before we get started, make sure you have the following prerequisites:

1. Basic knowledge of JavaScript and React.js
2. Node.js and npm installed on your system
3. Oracle database installed and accessible with appropriate credentials

Step 1: Setting Up the Project
Let's begin by creating a new React project using Create React App:


npx create-react-app react-oracle-crud-app

cd react-oracle-crud-app



Step 2: Setting Up the Backend Server
We'll create a backend server using Node.js and Express.js to handle the Oracle database operations. First, create a new directory for the backend:


cd backend-server

npm init -y

npm install express body-parser oracledb cors


Step 3: Connecting to Oracle and Implementing CRUD Operations
In the backend server's main file (index.js), establish the connection to your Oracle database:

// backend-server/index.js

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

const app = express();
const port = 5000;

app.use(bodyParser.json());
app.use(cors());

const connectionConfig = {
  user: 'YOUR_ORACLE_USERNAME',
  password: 'YOUR_ORACLE_PASSWORD',
  connectString: 'YOUR_ORACLE_CONNECTION_STRING',
};

async function init() {
  try {
    await oracledb.createPool(connectionConfig);
    console.log('Connected to Oracle Database.');
  } catch (err) {
    console.error('Error connecting to Oracle Database:', err);
  }
}

init();

// API routes for CRUD operations will be added here

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});


// Create
app.post('/api/items', async (req, res) => {
  try {
    const { name, description } = req.body;
    const conn = await oracledb.getConnection();
    const result = await conn.execute(
      'INSERT INTO items (name, description) VALUES (:name, :description)',
      [name, description]
    );
    await conn.close();
    res.json({ message: 'Item created successfully!' });
  } catch (err) {
    res.status(500).json({ error: 'Error creating item' });
  }
});

// Read
app.get('/api/items', async (req, res) => {
  try {
    const conn = await oracledb.getConnection();
    const result = await conn.execute('SELECT * FROM items');
    await conn.close();
    res.json(result.rows);
  } catch (err) {
    res.status(500).json({ error: 'Error retrieving items' });
  }
});

// Update
app.put('/api/items/:id', async (req, res) => {
  try {
    const { name, description } = req.body;
    const id = req.params.id;
    const conn = await oracledb.getConnection();
    const result = await conn.execute(
      'UPDATE items SET name = :name, description = :description WHERE id = :id',
      [name, description, id]
    );
    await conn.close();
    res.json({ message: 'Item updated successfully!' });
  } catch (err) {
    res.status(500).json({ error: 'Error updating item' });
  }
});

// Delete
app.delete('/api/items/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const conn = await oracledb.getConnection();
    const result = await conn.execute('DELETE FROM items WHERE id = :id', [id]);
    await conn.close();
    res.json({ message: 'Item deleted successfully!' });
  } catch (err) {
    res.status(500).json({ error: 'Error deleting item' });
  }
});

// ... (remaining code)
Replace 'YOUR_ORACLE_USERNAME', 'YOUR_ORACLE_PASSWORD', and 'YOUR_ORACLE_CONNECTION_STRING' with your actual Oracle credentials and connection string.



Step 4: Creating the Frontend Components
Now that the backend API routes are set up, let's focus on building the frontend components in React.

Create a new component called ItemList.js in the src folder: 
// server.js

// src/ItemList.js

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const ItemList = () => {
  const [items, setItems] = useState([]);
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');

  useEffect(() => {
    fetchItems();
  }, []);

  const fetchItems = async () => {
    try {
      const response = await axios.get('http://localhost:5000/api/items');
      setItems(response.data);
    } catch (error) {
      console.error('Error fetching items:', error);
    }
  };

  const handleCreate = async () => {
    try {
      await axios.post('http://localhost:5000/api/items', { name, description });
      setName('');
      setDescription('');
      fetchItems();
    } catch (error) {
      console.error('Error creating item:', error);
    }
  };

  const handleUpdate = async (id) => {
    try {
      await axios.put(`http://localhost:5000/api/items/${id}`, { name, description });
      setName('');
      setDescription('');
      fetchItems();
    } catch (error) {
      console.error('Error updating item:', error);
    }
  };

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:5000/api/items/${id}`);
      fetchItems();
    } catch (error) {
      console.error('Error deleting item:', error);
    }
  };

  return (
    <div>
      <h2>Item List</h2>
      <div>
        <input
          type="text"
          placeholder="Item Name"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <input
          type="text"
          placeholder="Item Description"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
        />
        <button onClick={handleCreate}>Create</button>
      </div>
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            <strong>{item.name}</strong> - {item.description}
            <button onClick={() => handleUpdate(item.id)}>Update</button>
            <button onClick={() => handleDelete(item.id)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>


Step 5: Putting It All Together (App.js)
Finally, integrate the ItemList component into the main App.js file:


// src/App.js

import React from 'react';
import ItemList from './ItemList';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>Oracle-React CRUD Application</h1>
      </header>
      <main>
        <ItemList />
      </main>
    </div>
  );
}

export default App;



Run the react app using following command:

npm start

Run the backend(index.js) file using following command:

node index.js

In this blog post, we explored how to build a dynamic web application with React.js and Oracle, enabling seamless CRUD operations. By combining the power of React's frontend capabilities with Oracle's robustness on the backend, you can build data-driven applications that efficiently manage data.

Post a Comment

0 Comments