Deleting

The final step is to implement deleting modules and as with the two previous frameworks, we will also implement this in the list of modules. Update the src/js/routes/modules/index.jsx, adding and updating the following bits of code to implement the module deletion.

...

export default function ModulesIndex() {
    let modules = null;
    function deleteModule(module) {
    m.request({
        method: "DELETE",
        url: `${api.base}/modules/${module.id}`,
    }).then(() => {
        m.request({
            method: "GET",
            url: `${api.base}/modules`,
        }).then((data) => {
            modules = data;
        });
    });
    }
    return {
    oninit: (vnode) => {
        m.request({
            method: "GET",
            url: `${api.base}/modules`,
        }).then((data) => {
            modules = data;
        });
    },
    view: (vnode) => {
        if (modules) {
        modules = modules.data.map((module) => {
            let key = `module-${module.id}`;

...

<li><a role="menuitem" aria-label="Leave" title="Leave" class="mdi mdi-delete warning" tabindex="0" onclick={(ev) => {deleteModule(module)}}></a></li>

...

As you can see, to delete an object, we send a request with the method 'DELETE' to the same URL from which we can get individual modules. With that we now have the basic pattern of JSONAPI requests, which are always to one of two, so-called, endpoints (“/type” for a collection of objects and “/type/id” for an individual object) with four different request types (“GET” to fetch data, “POST” to create new data, “PATCH” to update date, and “DELETE” to delete data). This is also known as a REST-ful API structure.

Important to note here is that after the delete request completes, we have to send another request to fetch the full list of modules. This is because unlike the Redux library or Ember, the Mithril request functionality does not implement any kind of tracking of the data it has loaded, it simply makes it available to the then callback function and if we, as we do, store the result (or part of it) in the component state, then updating that when the backend data is changed is our responsibility and we have to manually and explicitly update.