Skip to main content

JavaScript API Tutorials

Tutorial Home

Use the sxc data API to create/edit/delete data

This page uses the sxc data API to create data for the backend.


In this tutorial you'll learn how to:
  • Create data using the .create(...) method
  • Update data using the .update(...) method
  • Delete data using the .delete(...) method

Look at the content below to see the effect.
Name Birth date Poems Actions
Daniel 1/1/1949 74
SuperPoet 814 1/1/2021 90
SuperPoet 426 1/1/2021 979
SuperPoet 602 1/1/2021 38

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 _300-edit.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
// This tutorial uses turnOn, see https://app-dev.2sxc.org/tutorial-razor/en-bs4/Home/turn-on/home
// As soon as this variable exists, the page will start the code thanks to turnOn
window.editPoets = {
poetsSvc: null,
init: function({ moduleId }) {
// Create a $2sxc object using the current Module Id
const sxc = $2sxc(moduleId);
// Get the data Service - type PoetsToEdit has public create/delete permissions
poetsSvc = sxc.data('PoetsToEdit');
},
add: function() {
const newPoet = {
name: document.querySelector('#name').value,
birthdate: document.querySelector('#birthdate').value,
poems: document.querySelector('#poems').value
};
// Create data in the backend with .create(object) and reload page after
poetsSvc.create(newPoet).then(() => { alert('created poet, will reload'); location.reload(); });
},
delete: function(id) {
// Delete data in the backend with .delete()
poetsSvc.delete(id).then(() => { alert('deleted poet, will reload'); location.reload(); });
},
updateCount: function(id) {
// NOTE: Updated object doesn't need to contain all properties
const updatedPoet = {
Poems: Math.floor(Math.random() * 100).toString()
};
// Update data in the backend with .update()
poetsSvc.update(id, updatedPoet)
// After backend update, show the new number which the backend returned
.then(res => {
document.querySelector(`[data-poet='${id}']`).innerText = res.Poems
});
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX