Topic: Filling datatable with mysql in javascript
*_Expected behavior_*
Hi, I have a simple question about how to fill a datatable with data from a mysql database, using javascript (I'm working with electron js framework and mysql2 library)I know that datatable get data in JSON format or object array so: I get data from my table with a simple query, format data with mapping and get JSON. Put JSON into datatable with update statement and show datatable correctly.
*_Actual behavior_*
If I use an object array written manually it's all ok, but if I use my data getted and formatted from my database i can't show results...But with console.log() I can see data exists and seems formatted correctly.
Resources (screenshots, code snippets etc.)
// This works
const data_example_manual = [{ name : 'name', surname : 'surname', notes : 'notes',},{...},{...}];
// This doesn't works
const connection = await connectToDB('test');
const query = 'SELECT name, surname, notes FROM table';
const results = await connection.query(query);
const customJSON = results.map((row, index) => ({
index: index + 1,
name: row.name,
surname: row.surname,
notes: row.notes
}));
// This log seems to show data in right format, but when I use them datatable not show rows
console.log(customJSON);
Thanks for your help.
kpienkowska staff answered 2 years ago
How are you passing your data to datatable? Console.log display data when they are "ready". Also, do you get any console errors?
You need to use the update
method if you work with asynchronous data:
https://mdbootstrap.com/docs/standard/data/datatables/#section-async-data
Verlino pro premium priority commented 2 years ago
Thank you for reply.I was trying to save the result of the .map in another array for my convenience, however i found that it wasn't necessary so now i use the result of the .map directly and everything works.However, for information, I put the code I used so maybe we can find a useful solution in other situations: \
[...]
const array = new Array();
const messages = values.map((row) => { name: row.name, surname: row.surname, note: row.note,});
array.push(messages);
return array;
[...]
Thank you.
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- User: Pro
- Premium support: Yes
- Technology: MDB Standard
- MDB Version: MDB5 6.3.1
- Device: Laptop
- Browser: Chromium
- OS: Ubuntu
- Provided sample code: No
- Provided link: No