Skip to main content
Home  › ... 2sxc Apps

JavaScript API Tutorials

Tutorial Home

Use the sxc data API to get backend data

This page uses the sxc data API to get data from the backend and display it in a table with JavaScript.


In this tutorial you'll learn how to:
  • Create a $2sxc object using the current Module Id
  • Use the correct data source using .data()
  • Read data using the .getOne(id) query method
  • Read data using the .getAll() query method

Look at the content below to see the effect.
Name Birthdate Poems

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Source Code of _200-get data.js

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Use an IFFE to ensure the variables are not exposed globaly
// See https://developer.mozilla.org/en-US/docs/Glossary/IIFE
(() => {
// This is a more modern JS feature to deconstruct parameters
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
function init({ moduleId }) {
// Create a $2sxc object using the current Module Id
const sxc = $2sxc(moduleId);
// Get the data source using .data('xy')
const poetsSvc = sxc.data('Poets');
// Read data from the backend data source with the .getAll() query
poetsSvc.getAll().then((poets) => {
// pass poets to displayPoets
displayPoets(poets);
// Get data of first poet with .getOne(id) query and log it in the console
poetsSvc.getOne(poets[0].Id).then((poet) => console.log(`Queried poet using .getOne(): ${poet}`));
});
}
// Display example data in table
function displayPoets(poets) {
Array.prototype.forEach.call(poets.reverse(), (poet, poetIndex) => {
// Make sure only 3 elements are shown
if (poetIndex >= 3) return
let tr = document.createElement('tr')
addField(tr, poet.Name);
addField(tr, new Date(poet.BirthDate).toLocaleDateString());
addField(tr, poet.Poems);
document.querySelector('#example-content > tbody').appendChild(tr)
});
}
function addField(tr, text) {
let td = document.createElement('td')
td.innerText = text
tr.appendChild(td)
}
// This tutorial uses turnOn, see https://app-dev.2sxc.org/tutorial-razor/en-bs4/Home/turn-on/home
const sDT = window.sxcDataTutorial200 = window.sxcDataTutorial200 || {};
sDT.init = sDT.init || init;
})();
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX