DataTable failing to refresh after updating data

I'm facing a challenge in re-initializing a DataTable within my Vue.js application after updating the data. Below is the snippet of code I am using:

  • template :

.

<table ref="tableUtamaAlamat" id="tableUtamaAlamat" class="display datatable-custom" style="width: 100%">
    <thead>
        <tr>
            <th>No</th>
            <th>address</th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="(row, index) in tableDataUtamaAlamat" :key="index">
            <td>{{ index + 1 }}</td>
            <td>{{ row.alamat }}</td>
        </tr>
    </tbody>
</table>
  • script part (methods):
initDataTableAlamat() {
   $(this.$refs.tableUtamaAlamat).DataTable({
       paging: true,
       searching: true,
       ordering: false,
       info: true,
       dom: '<"top-toolbar"fB>rt<"bottom-toolbar"ip><"clear">',
       buttons: [
           {
               text: '...Svg path for a button...',
               action: function (e, dt, node, config) {
                   $("#modalUtamaAlamat").removeClass("hidden");
               },
           },
       ],
       language: {
           search: "Pencarian:",
           lengthMenu: "Tampilkan _MENU_ entri",
           info: "Menampilkan _START_ sampai _END_ dari _TOTAL_ entri",
           infoEmpty: "Tidak ada entri tersedia",
           infoFiltered: "(difilter dari _MAX_ total entri)",
           zeroRecords: "Tidak ada entri yang cocok ditemukan",
           paginate: {
               next: "",
               previous: "",
           },
       },
       initComplete: function () {
           $(".wrapper-datatable-custom .top-toolbar .dt-search .dt-input").attr("placeholder", "Pilih salah satu...");
       },
   });
},
async getAlamatByUserID() {
    try {
        const payload = { user_id: this.$store.state.auth.user.user.user_id };
        const response = await this.$store.dispatch("vendor/getAlamatByUserID", payload);
        this.tableDataUtamaAlamat = response.data.data;
        // Re-initialize DataTable
        this.$nextTick(() => {
            const table = $(this.$refs.tableUtamaAlamat).DataTable();
            if (table) {
                table.destroy(); // Destroy the existing DataTable instance
            }
            this.initDataTableAlamat(); // Re-initialize DataTable
        });
    } catch (error) {
        console.error("Error fetching alamat:", error);
    }
},
async deleteAlamat(alamat_id){
    try {
        const payload = { alamat_id :  alamat_id}; 
        const response = await this.$store.dispatch('vendor/deleteAlamat', payload);
        console.log(response)
        await this.getAlamatByUserID(); 
        return response;
    } catch (error) {
        console.error('Error saving alamat:', error);
        return error;
    }
}

explain :

  • Therefore, the objective is to re-initialize the datatable when the deleteAlamat action is triggered. Upon calling this function, getAlamatByUserID is executed to update the data stored in this.tableDataUtamaAlamat. Subsequently, even though the updated data is logged, the issue lies with the datatable not rendering properly. The row count persists, and a page refresh is required to reflect the changes in UI.

  • The setback seems to be related to the asynchronous behavior of async/await. When utilizing hardcoded data, the re-initialization process completes successfully. Any suggestions or insights would be greatly appreciated.

any suggesttion? thank you in advance

EDIT : I forgot to mention error, becaouse there is no error when re-initializing part

EDIT : Ayyone? i think the issue is related to async/await timing. because, when I fetch the data with harcoded data the re-initializing is succeed.

Answer №1

It's a smart move to reset the DataTable instance before initializing it again. I suggest using a setTimeout function to allow the DOM to update before reinitializing the DataTable.

Here is an improved method:

async getAddressByUserID() {
    try {
        const payload = { user_id: this.$store.state.auth.user.user.user_id };
        const response = await this.$store.dispatch("vendor/getAddressByUserID", payload);
        this.mainAddressTableData = response.data.data;

        this.$nextTick(() => {
            const table = $(this.$refs.mainAddressTable).DataTable();
            if (table) {
                table.clear().destroy();
            }
    
            $(this.$refs.mainAddressTable).find('tbody').empty();

            // Re-initiate the DataTable after a brief delay
            setTimeout(() => {
                this.initializeAddressDataTable(); 
            }, 100);
        });
    } catch (error) {
        console.error("Error fetching address:", error);
    }
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can JavaScript be used to modify the locale of a web browser?

Is it possible to programmatically set the window.navigator.language using AngularJS? I am exploring different methods to achieve this. At the moment, I rely on a localization service to handle my i18n localization switching. ...

Documentation guide: best practices for indicating optional return values

I am tasked with properly documenting a function using JSDoc. The function triggers something if it returns true, otherwise it does not. However, the return value must always be of boolean type. Here is my proposed JSDoc documentation: * @return {boolean ...

Tips for stopping html form from refreshing upon submission

Hello, despite extensive searching and testing, I am still unable to locate the issue and therefore I am reaching out to seek your assistance in resolving my problem. Within a form that I have created, upon clicking the submit button, a javascript functio ...

How to convert DateTime to UTC in TypeScript/JavaScript while preserving the original date and time

Consider the following example: var testDate = new Date("2021-05-17T00:00:00"); // this represents local date and time I am looking to convert this given Date into UTC format without altering the original date and time value. Essentially, 2021-0 ...

What is the best method to determine the cumulative time spent filling out a text box on a web page using Angular?

I am working on a web page that contains two text boxes. My goal is to track the total time spent inside each box when the user clicks the submit button at the end of the page. clickInside() { this.text = 'clicked inside'; this.wasIns ...

The Material-UI dialog is experiencing a flickering issue when incorporating Redux to manage the open

I am currently facing an issue with moving the open state of a material-ui dialog to redux in order to prevent it from closing during a rerender. However, I am encountering difficulties with the dialog's behavior when a rerender occurs. Even though th ...

Synchronous AJAX requests do not function properly in IE and Firefox, but they do work in Chrome and Safari

Attempting to measure download speed using an AJAX call. Below is the code snippet: var start = new Date(); $.ajax ({ url: 'https://www.example.com/perftest/dummyFile1024', cache: false, success : function() { var total = ( ...

Is it possible to replicate this JavaScript syntax in C++?

As someone who frequently writes JavaScript, I find myself particularly drawn to the syntax of this feature. While I'm uncertain about its nomenclature, here's an illustrative example: object.function1().function2().function3() I understand tha ...

What is the functionality of react.js state?

As I delve into learning React.js, I've been quite impressed with its state management capabilities. However, I'm curious about the technical workings behind it. Does React.js utilize cookies or browser storage for its state management? ...

Function executed many times during click action

I have developed a web application that allows users to input any keyword or statement and receive twenty results from Wikipedia using the Wikipedia API. The AJAX functionality is working perfectly. The app should dynamically create a DIV to display each r ...

The Vuetify Navigation Drawer functions correctly initially but then suddenly halts

When utilizing a Vuetify navigation drawer, I encountered an issue with the element that triggers its opening. The trigger element, v-toolbar-side-icon, is located in a separate component within the header section. To manage the open/close state of the dra ...

Is there a more efficient method in ThreeJS to generate and display a lush woodland filled with unique trees?

I am facing the challenge of rendering a vast forest comprised of over 100,000 simplistic trees in ThreeJS. It is not feasible to create individual meshes for each tree. Currently, I am using GeometryUtils.merge to combine the trees into one large geometry ...

Events in EmberJS that occur after the content has been modified

Need assistance with implementing an alert event for a new tab added to the default ones. Solution: Develop a TabsController Create an initilizerView which uses a list parameter to manage the TabsController.Content Upon insertion of the view, add the ac ...

Guide to redirecting data from an external POST request to a customer through a GET request

Within my Express application, I am currently dealing with both incoming POST requests containing a payload from an external source and GET requests sent by my client: router.post('/liveReleaseStore', (req, res) => { let data = req.body.m ...

Troubleshooting Vue/Vuetify: Inability to use the Esc key to show/hide dialog in parent component

I have been utilizing the vuetify library in my project. I encountered an issue where the ESC key does not work when opening a dialog from a child component to a parent component for the first time. It seems like there might be a mistake in my implementati ...

Struggling to make the AJAX script function properly

I have a table containing a list of transactions and I am attempting to update the table contents at specific intervals. The web page is hosted on a Linux Red Hat server, and currently, only the AJAX functionality is not functioning as expected. <!do ...

The API response in JSON format is displaying as "undefined"

My current code is running as follows: const request = require('request') const apiKey = 'XXXXXXXXXXXXXX' var dat; let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx' let qs = { q: '-34.48,150.92&ap ...

Locate relevant information within the arrays through the process of filtering

For my collection, I am looking to match the operator_name based on date and then further narrow it down by matching shift_name within an array { "_id": "5eb301bc0218ff48b724a486", "date": "2020-07-02T00:00:00.000Z", "shift_wise": [{ "_id": ...

Guide on setting a client-side cookie in NextJS 14

I attempted to store a cookie in the client's browser using Nextjs 14 app router within the API folder, but unfortunately, it did not function as expected Below is the provided code snippet: app/api/auth/login/route.js const { NextResponse } = requi ...

AngularJS navigates to specific URL paths instead of only displaying the corresponding HTML pages

Building a simple AngularJS application using the angular-seed starter template consists of: index.html app.js home/home.html home/home.js My objective is to navigate to home.html when clicking on the Home li item with the href="/home". However, the cur ...