To fetch data from MySQL in a React JS application, you can follow these steps:

  1. Install the required dependencies:
  • Install the mysql package using npm or yarn:
    npm install mysql
    or
    yarn add mysql
  • Additionally, you may also need to install dotenv if you plan to store your database credentials in a .env file:
    npm install dotenv
    or
    yarn add dotenv
  1. Create a database connection file:
  • Create a new file, e.g., db.js, to establish a connection with your MySQL database.
  • Import the mysql package and create a connection object using your database credentials: const mysql = require('mysql'); const connection = mysql.createConnection({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME }); module.exports = connection;
  1. Create a component to fetch and display data:
  • Create a new component, e.g., DataComponent.js, where you want to fetch and display the data.
  • Import React and any other required dependencies: import React, { useState, useEffect } from 'react'; import axios from 'axios'; // You may need to install the axios package if not already installed.
  • Define the component and use the useState hook to manage the fetched data: const DataComponent = () => { const [data, setData] = useState([]); useEffect(() => { fetchData(); }, []); const fetchData = async () => { try { const response = await axios.get('/api/data'); // Assuming you have set up an API endpoint for fetching data. setData(response.data); } catch (error) { console.error('Error fetching data:', error); } }; return ( <div> <h1>Data Component</h1> <ul> {data.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); }; export default DataComponent;
  1. Set up an API endpoint on your server to fetch data from the database:
  • Create a new file, e.g., api.js, to define your API endpoints.
  • Import Express and your database connection: const express = require('express'); const connection = require('./db'); // Assuming the database connection file is in the same directory.
  • Create a router and define an endpoint to fetch data: const router = express.Router(); router.get('/data', (req, res) => { const query = 'SELECT * FROM your_table'; // Replace "your_table" with the actual table name. connection.query(query, (error, results) => { if (error) { console.error('Error fetching data:', error); res.status(500).json({ error: 'Internal server error' }); } else { res.json(results); } }); }); module.exports = router;
  1. Set up your server:
  • In your main server file (e.g., server.js), import and use the API router:
    “`javascript
    const express = require(‘express’);
    const apiRouter = require(‘./api’); // Assuming the API router file is in the same directory. const app = express(); app.use(‘/api
Leave A Comment