Fetching data from database

UI Components for React
Post Reply
ddao
Posts: 4
Joined: 18 Nov 2020, 23:25

19 Nov 2020, 18:45

Hello all,
I'm new to practically everything (react, primereact, and java script). So sorry if the question is trivia.

Anyhow, I'm able to follow a long this example and actually run the example on my suse box fine: https://primefaces.org/primereact/showc ... /paginator

Question is, how do I fetch it from a sql database and populate the data table?

From the example, the data are fetched from a file 'customers-large.json' via CustomerService.js
I have mysql server running with data that I can use. So I'm mimicking CustomerService.js and write DbService.js to fetch the data (see below).
I test DbService.js and it returns the data fine. The thinking is once I'm able to query the database, I just need to populate the data into primereact table. However I don't know how to populate it.
Any example that I can use?



---- DbService.js ----------------------------------
const mysql = require('mysql');
const express = require('express');
const bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());



var mysqlConnection = mysql.createConnection({
host:'10.10.10.10',
user: 'root',
password: 'a',
database: 'testresults',
multipleStatements: true
});

mysqlConnection.connect((err)=>{
if(!err)
console.log('DB connection succeeded.');
else
console.log('DB connection failed\nError: ' + JSON.stringify(err, undefined, 2));
})


app.get('/tests', (request, response)=>{
mysqlConnection.query('SELECT * from testResult', (err, rows, fields)=>{
if (!err)
response.send(rows);
else
console.log(err);
})
});

pavel.tavoda@f4s.eu
Posts: 12
Joined: 21 Oct 2020, 10:54

22 Nov 2020, 12:12

At first I strongly recommend to setup proxy in your package.json like:
"proxy": "http://localhost:8809",
which will bridge calls to your server otherwise you will have problems with CORS (you can setup it without proxy but you have to know what you are doing).
Than all 'unknown' calls are bridged to your server/service where data fetch is made.

Than on client side it's best to use useEffect() hook (in functional component NOT CLASS) something like:

Code: Select all

const [page, setPage] = useState(1);
const [data, setData] = useState(null);

useEffect(() => {
    fetch('/service/getSomething?page='+page)
    .then(res => res.json())
    .then(res => setData(res.data));
}, [page]);

return (
....
<Table data={data}/>
...
)
For general discussion about React hooks and useEffect check React manual:
https://reactjs.org/docs/hooks-effect.html

For examples google something like 'react useEffect fetch' there are milion articles about it e.g.:
https://www.robinwieruch.de/react-hooks-fetch-data

For advanced setup how to fetch and cache data 'better' way look at:
https://react-query.tanstack.com/

Post Reply

Return to “PrimeReact”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 3 guests