Home > Software engineering >  Updating object from promise reactively with Svelte and Jquery datatable results in Uncaught promise
Updating object from promise reactively with Svelte and Jquery datatable results in Uncaught promise

Time:07-04

I am slowly but surely migrating a jquery project to Svelte, but some features such as datatables are just a bit more mature in jquery. So referencing the Svelte html example I tested the reactive feature of Svelte by updating an Array of objects from a server side call with a promise; and then redrawing the table. The purpose being to bring the implementation closer to native Svelte.
But although I get the table to render, when I plugged the jquery search feature with the Svelte reactively declared variable, I only get to update the table once before I receive an error: Uncaught (in promise) TypeError: e.parentNode is null.

Can someone please help me to understand why this will happen?

// Load.svelte
<script context="module">
    import {env} from './EnvUtils.js';
    import axios from "axios";
    const wait = delay => new Promise(resolve => setTimeout(resolve, delay));
    let perPage = 10;

    console.log(env);

    const BASE_URL = env.host   'blogged-posts';

    const config = {
        headers: {
            "X-Requested-With": "XMLHttpRequest",
            "Accept": "application/json",
            'Content-Type': 'application/json',
            "X-CSRF-Token": document.querySelector('meta[name="csrf-token"][content]').content
        }
    }

    export async function fetchData(page, search = undefined) {
        await wait(500);
        console.log(page, search);
        try {
            const getUrl = (search!==undefined) ? `${BASE_URL}?page=${page}&per_page=${perPage}&search=${search}&delay=1` : `${BASE_URL}?page=${page}&per_page=${perPage}&delay=1`;
            const response = await axios.get(getUrl, config);
            const { data } = await response;
            console.log("data:", data);
            
            return data && data['data']!==null && data['data']!==undefined ? data.data : [];
        } catch (error) {
            console.error("Error: ", error);
        }
    }
</script>

Above is the Load.svelte module that uses axios to retrieve remote data.

// Blog.svelte
<script>
    import { onMount, tick } from "svelte";
    import {env} from './utils/EnvUtils.js';
    import {fetchData} from "./utils/Load.svelte";
    import jQuery from "jquery/dist/jquery";
    import initDt from 'datatables.net-dt';

    console.log(env, jQuery, initDt);
    let search;
    let currentPage = 1;
    let el // table element
    let table // table object (API)
    
    $: dataPromise = fetchData(currentPage, search);
    
    onMount(() => {
        dataPromise.then(tick).then(() => {
            table = jQuery(el).DataTable();
            // search input function
            table.on('search.dt', function() {
                var input = jQuery('.dataTables_filter input')[0];

                dataPromise = fetchData(table.page.info().page, input.value);

                dataPromise.then(tick).then(() => {  // error occurs within this promise on searching more than one letter
                    console.log("redraw");
                });
            });
        })
    });
</script>
<table bind:this={el}  style="width:100%">
    <thead>
      <tr>
        <th>Title</th>
        <th>Updated</th>
      </tr>
    </thead>
    <tbody>
      {#await dataPromise}
      <tr><td>...fetching</td></tr>
      {:then rows}
        {#each rows as row}
          <tr>
              <td>{row.title}</td>
              <td>{row.updated_at}</td>
          </tr>
        {/each}
      {/await}
    </tbody>
    <tfoot>
      <tr>
        <th>Title</th>
        <th>Updated</th>
      </tr>
    </tfoot>
  </table>

Above is the Blog.svelte component that awaits the promised dataPromise before rendering the datatable. Within the search input of the datatable; I call upon the fetchData function to hand new data to the dataPromise reactively declared variable when the search term is changed. The promise will with long search terms be called multiple times and upon finishing the promise update the table multiple times.
To overcome this issue I created a Svelte store writable onReady variable to check if a promise is busy.

// Store.svelte
<script context="module">
    import { writable } from 'svelte/store'

    export const onReady = writable(true)
</script>
// ... amendments Load.svelte
    export async function fetchData(page, search = undefined) {
        onReady = false;
// before return
        onReady = true;

// ... amendments Blog.svelte
// before calling promise in input function check onReady?
       if (!onReady) return false;
       dataPromise = fetchData(table.page.info().page, input.value);

This did not solve the issue: Can someone please help?

CodePudding user response:

You cannot just replace HTML that is managed by the Datatables. You would have to update the underlying data instead.

As your data is loaded asynchronously, this should not be done that way anyway. You should set serverSide to true and possibly use ajax to supply a custom function for fetching and formatting the data, if you cannot or do not want to implement a server endpoint that conforms to the default request/response format.

Not doing it this way also interferes with the filtering, which happens client-side by default. When server-side processing is enabled, Datatables will also automatically apply a search delay of 400ms which can be changed via the searchDelay option.

Example:

<script>
    import jQuery from '[email protected]';
    import dt from '[email protected]';
    import { onMount } from 'svelte';
    
    let table;
    let tableApi;
    
    onMount(() => {
        dt(window, jQuery);
        tableApi = jQuery(table).DataTable({
            serverSide: true,
            ajax: async (data, callback, settings) => {
                const json = await fetch('https://jsonplaceholder.typicode.com/posts')
                    .then(r => r.json());
                
                // This should happen on server
                const search = data.search.value;
                const filtered = json.filter(x => !search || x.title.indexOf(search) != -1);
                const page = filtered.slice(data.start).slice(0, data.length);

                // Expected format for callback:
                callback({
                    draw: data.draw,
                    data: page,
                    recordsFiltered: filtered.length,
                    recordsTotal: json.length,
                });
            },
            columns: [
                // Set JSON data source for columns
                { data: 'id' },
                { data: 'title' },
            ]
        });
    })
</script>

<svelte:head>
    <link rel=stylesheet href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css"/>
</svelte:head>

<table id=table bind:this={table}>
    <thead>
        <tr>
            <th>ID</th>
            <th>Title</th>
        </tr>
    </thead>
</table>

REPL

There is no point in using Svelte here, the API is not meant for it.

The only time Svelte can/should be used, is if a column actually contains HTML. For that the columns.render function can be used. Unfortunately components cannot be inlined and the Datatables API also does not appear to offer a method for just rendering an entire row, so each cell that requires Svelte-powered rendering has to be extracted to a separate component.

REPL example with column renderer

(Paging causes new tabs to be opened in the REPL for some reason.)

  • Related