REST Source Data for column called from columns properties
REST Source Data for column called from columns properties
Hello everybody,
I want to call a url to supplement data I already have in my datatable. So my data shall consist of both local and external ressources. In my given example, the column "id" shall be filled with values from the object data, whereas the column "RestCalledValue" shall be received from the given URL.
I have constructed a fiddle here: https://jsfiddle.net/mxhdwfz6/2/
My js code can be found below:
let data = [
{
"id": 1
},
{
"id": 2
}
]
$(function () {
var table = $('#table').DataTable({
data: data,
columns: [
{
data: "id"
},
{
data: function (row, type, set, meta) {
getRestDataForId(row.id);
},
defaultContent: "-"
}
]
});
});
function getRestDataForId(id) {
fetch('https://jsonplaceholder.typicode.com/todos/' + id)
.then(response => response.json())
.then(data => data.title)
}
For completeness, here an html-sample:
<table id="table">
<thead>
<tr>
<th>Id</th>
<th>RestCalledValue</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I expect the column "RestCalledValue" to have the titles coming from the given url, but I only get the default values (because the promise is not resolved properly?) I read from the documentation, that the value returned from the function
data: function (row, type, set, meta) {
getRestDataForId(row.id);
}
will be the result of the table. How can I properly return the value from here?
Looking forward to your input!
Thanks for the great tool and best regards.
Answers
columns.data
(and alsocolumns.render
) do not allow async functions.In fact, I would seriously encourage you not to even attempt to use an async function in either of them. Consider for example a table that only has 10 rows of data. DataTables needs, at a minimum, to determine the filtering data for the column, its sorting data, the data type and of course the display. That is up to 4 calls per cell. 10 rows, single column - that is up to 40 Ajax requests to the server just to display 10 rows and a single column!
By far the best thing to do here is to combine the data on the server and give a single feed to DataTables, so it only has to make a single async call to get the data for the whole table.
If you must make two calls, do it before you initialise DataTables - 1. get the basic data, then 2. get the additional data for each row (ideally in a single request for all rows), finally 3. initialise the DataTable with that data.
Allan