I am new to MDBootstrap and I am trying to learn how to use the DataTables. I have seen the examples on their website for Async table updates, however I found it confusing to convert it to my use case.
I am interested in learning how to use the async table update method specifically since I would like my table to update four columns dynamically based on filters that I am collecting from Dropdowns.
I would like the table to get its data by calling a PHP endpoint that will return data back in JSON and I am not understanding how to use the asyncTable.update()
method (based on their example).
For the sake of simplicity, let's assume the PHP endpoint returns JSON that looks similar to this:
[ { "a": "a string", "b": "another string", "c": "another string", "d": "another string" }, { "a": "a string", "b": "another string", "c": "another string", "d": "another string" }]
Based on the example code snippet from the MDBootstrap site (listed below), how do I modify the code to call my own endpoint? I do not understand the javascript syntax within the .update()
method of the example code:
const columns = [
{ label: 'A', field: 'a' },
{ label: 'B', field: 'b' },
{ label: 'C', field: 'c' },
{ label: 'D', field: 'd' },
];
const asyncTable = new mdb.Datatable(
document.getElementById('datatable'),
{
columns,
}
);
//var url = 'MY OWN PHP ENDPOINT URL';
var url = 'https://jsonplaceholder.typicode.com/users';
fetch(url)
.then((response) => response.json())
.then((data) => {
asyncTable.update(
{
rows: data.map((user) => ({
...user,
address: `${user.address.city}, ${user.address.street}`,
company: user.company.name,
})),
},
{ loading: false }
);
});
});
I would appreciate any help on how to use this method using my own end point and not the example endpoint and data structure presented.
Thanks
you have to change link in fetch
for your endpoint's URL
fetch('https://custom-api.com/rows')
The update() method takes two parameters: data
and options
. Upon changing the URL you have to modify the data
parameter to correspond to your data. In your example it will look like:
fetch('https://your-url.com/rows')
.then((response) => response.json())
.then((data) => {
asyncTable.update(
{
rows: data.map((row) => ({
a: row.a,
b: row.b,
c: row.c,
d: row.d
})),
},
{ loading: false }
);
});
this example might look cleaner for you: https://mdbootstrap.com/snippets/standard/m-duszak/3000204#js-tab-view