Fetching data from database

UI Components for React
Post Reply
Posts: 6
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();

var mysqlConnection = mysql.createConnection({
user: 'root',
password: 'a',
database: 'testresults',
multipleStatements: true

console.log('DB connection succeeded.');
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)

Posts: 13
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(() => {
    .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:

For examples google something like 'react useEffect fetch' there are milion articles about it e.g.:

For advanced setup how to fetch and cache data 'better' way look at:

Posts: 4638
Joined: 29 Jun 2013, 12:38

12 Dec 2020, 03:38

Thanks a lot, @pavel.

Best Regards,

Post Reply

Return to “PrimeReact”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 2 guests