skip to Main Content

How do i fetch data from my MySql database as json and then use it in react js…? actually i’m new to React and MySql so i just don’t know much about it.. Please help

7

Answers


  1. first, you have to solve the console error of key of react, give the key wherever you

    Login or Signup to reply.
  2. React is not allowed to connect to MySql directly. We need NodeJs to start a back-end server which supporting HTTP API.
    enter image description here

    You can watch this video, and try to create your demo.

    React Node.js MySQL CRUD Tutorial for Beginners

    Login or Signup to reply.
  3. I agree with YinPeng.Wei’s idea for setting up a backend server to retrieve data from database. The majority programming language for backend development have packages or libraries to connect with Database.

    A similar question was asked years ago about How to connect to SQL Server database from JavaScript in the browser?. The answer is you could do that but it is high discouraged.

    The general idea is to create a simple backend server which responds to your React frontend requests. Backend retrieves data from MySQL via sql query, then serialize searched data into JSON format and gives back to your frontend.

    Not sure which type of programming language would you choose for backend development. I would do either one of Python, C#, Java for a quick demo.

    Login or Signup to reply.
  4. Typically, you are using React to connect to another app (backend) via an API e.g. REST, THAT backend is the one who connect to the database and passes the data to your React app.

    Your react app doesn’t even know there is a database, all he knows is the backend that’s feeding him. without him he’s just a pretty looking dead app.

    now from your backend, you have two ways, using languages built-in driver to connect to your database directly (hand writing SQL statements), Or you may use an ORM, just google "js orm" and you will find many.

    As a start, you need to learn more about creating a simple REST API with whatever language you choose, and then simply use fetch("http://example.com/whatever").then(res=> JSON.parse(res)).then(res=> console.log(res))

    the code above should show you whatever you see on the screen when you actually visit the URL inside fetch() from the browser, just text.

    REST itself is just a way to use HTTP that people like.

    the browser itself is just another client (like your React app), if he can do it so does your app.

    Login or Signup to reply.
  5. The backend has some URLs called apis which send some requests as get or post. The react catches that request via fetch or axios and update its components states. People use fetch or axios library to fetch that request and to handle state management libraries like redux if it is very large and uses built-in react API like reducer hooks and some others.

    Below is an example of how to use fetch

    import { useState, useEffect } from 'react';
    
    function App() {
      const [data, setData] = useState([]);
    
      useEffect(() => {
        fetch('http://localhost:3000/data')
          .then((response) => response.json())
          .then((data) => setData(data));
      }, []);
    
      return (
        <div>
          {data.map((item) => (
            <div key={item.id}>
              <h2>{item.title}</h2>
              <p>{item.description}</p>
            </div>
          ))}
        </div>
      );
    }
    
    export default App;
    
    Login or Signup to reply.
  6. create a connection to your MySQL database in Serverside (Node js)

    const mysql = require('mysql');
    const connection = mysql.createConnection({
      host: 'localhost',
      user: 'your_user',
      password: 'your_password',
      database: 'your_database'
    });
    
    connection.connect((err) => {
      if (err) throw err;
      console.log('Connected!');
    });
    

    Add an API route to fetch the data from the MySQL database

    app.get('/data', (req, res) => {
      connection.query('SELECT * FROM your_table', (error, results, fields) => {
        if (error) throw error;
        res.send(JSON.stringify(results));
      });
    });
    

    fetch data in your react component

    fetch('/data')
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
    

    I hope it should work

    Login or Signup to reply.
  7. You need a backend to communicate from React to MySQL. This backend need an API which you can export data directly from MySQL based on a command. Basically, if you wanted to make a query you would need to do it via a HTTP API. It could look something like this:

    const mysql = require("mysql2");
    const express = require("express");
    const app = express();
    const pool = mysql.createPool({
        host: 'localhost', // your server ip or domain name
        user: 'root', // username for db
        password: '', // server password
        database: 'test', // db
        waitForConnections: true,
        connectionLimit: 10,
        maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
        idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
        queueLimit: 0
      });
    
    
    
    function Query(SQLQUERY) {
        return new Promise((resolve, reject) => {
            pool.query(SQLQUERY, function(err, rows, fields) {
                // Connection is automatically released when query resolves
                console.log(err)
                resolve(rows);
            });    
        });
    }
    
    
    app.get("/", async function(req, res) {
        let SQLQUERY = req.query.sqlquery;
        console.log(SQLQUERY)
        let query = await Query(SQLQUERY);
        res.send(query);
    })
    
    app.listen(80)
    

    The only thing you need now is to send a HTTP request/fetch like this to get the response of the sql query.

    http://localhost/?sqlquery=SELECT * FROM test;
    

    PS I would **not advise to use this solution directly, as it is not safe, since it allows anybody to execute any query in your database. But it shows you what is possible.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search