React CRUD Tutorial with Node
Welcome to our tutorial on fetching data from MySQL in React JS. In this article, we’ll walk you through step-by-step on how to create a CRUD (Create, Read, Update, Delete) application using Node.js as the backend and React.js as the frontend.
Step 1: Set up the Node.js backend
First, you’ll need to set up a Node.js backend to handle the database operations. You can do this by creating an Express server with endpoints for creating, reading, updating, and deleting data from your MySQL database.
“`javascript
const express = require(‘express’);
const app = express();
const mysql = require(‘mysql’);
// Create a connection to the MySQL database
const connection = mysql.createConnection({
host: ‘localhost’,
user: ‘root’,
password: ‘password’,
database: ‘my_database’
});
// Connect to the database
connection.connect();
// Create an endpoint for fetching data
app.get(‘/data’, (req, res) => {
connection.query(‘SELECT * FROM my_table’, (error, results) => {
if (error) {
res.status(500).send(error);
} else {
res.status(200).json(results);
}
});
});
// Add other endpoints for creating, updating, and deleting data
app.listen(3000, () => {
console.log(‘Server is running on port 3000’);
});
“`
Step 2: Set up the React.js frontend
Next, you’ll need to set up a React.js frontend to consume the data from the Node.js backend. You can do this by creating components to display the data and make requests to the backend to perform CRUD operations.
“`javascript
import React, { useState, useEffect } from ‘react’;
import axios from ‘axios’;
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios.get(‘/data’);
setData(result.data);
};
fetchData();
}, []);
return (
My Data
-
{data.map(item => (
- {item.name}
))}
);
};
export default App;
“`
Step 3: Display the data in the React app
Now that you have set up both the Node.js backend and the React.js frontend, you can display the fetched data in your React app. Simply import the App component and render it in your root component.
“`javascript
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import App from ‘./App’;
ReactDOM.render(
document.getElementById(‘root’)
);
“`
And that’s it! You now have a fully functional CRUD application using Node.js, MySQL, and React.js. You can further expand the app by adding functionality for creating, updating, and deleting data, but this tutorial will get you started with fetching data from MySQL in React JS.
In react js
Plz send me video of multiple dynamic list filtering of data
Why I am getting Cors policy error?