While in print view, the old datatable is seen, not the updated one?

While in print view, the old datatable is seen, not the updated one?

waqaranwar2021waqaranwar2021 Posts: 16Questions: 3Answers: 0

Description of problem:
Generic Datatable component code:

import React, { useEffect, useRef, useState } from 'react';
import $ from 'jquery';
// import 'bootstrap/dist/css/bootstrap.min.css';
import 'jquery/dist/jquery.min';
import "datatables.net-dt/js/dataTables.dataTables";
import "datatables.net-dt/css/dataTables.dataTables.min.css";
import "datatables.net-buttons/js/buttons.colVis";
import "datatables.net-buttons/js/buttons.html5";
import "datatables.net-buttons/js/buttons.print";
import "datatables.net-buttons/js/dataTables.buttons";
// import 'jszip';
import JSZip from 'jszip'; 
import 'pdfmake';
// import 'pdfmake/build/pdfmake';
// import 'pdfmake/build/vfs_fonts';
import pdfMake from "pdfmake/build/pdfmake";
import pdfFonts from "pdfmake/build/vfs_fonts";
import DataTable from 'datatables.net-buttons-dt';
import JsPDF from "jspdf";
import html2canvas from "html2canvas-pro";
import * as html2pdf from 'html2pdf.js'

window.JSZip = JSZip;
pdfMake.vfs = pdfFonts.pdfMake.vfs;


const MasterDataTable = (prop) => {
  const { tableId, tableData } = prop
  const dataTableRef = useRef(null);

  useEffect(() => {

        // if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
          // $(`#${tableId}`).DataTable().destroy();
          // console.log("destroyed")
        // }
        // if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
          // $(`#${tableId}`).DataTable().destroy();
          // console.log("destroyed2")
        // }
        // if (dataTableRef.current) {
          // dataTableRef.current.destroy();
          // dataTableRef.current = null
          // dataTableRef.current
          // .rows()
          // .invalidate()
          // .draw();
        // }
        // if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
        //   $(`#${tableId}`).DataTable().destroy(true);//.clear().draw(false)
        //   console.log(`DataTable with ID #${tableId} destroyed.`);
        // }
        // if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
        //   $(`#${tableId}`).DataTable().clear().draw(); // Only clear and redraw instead of destroy
        //   console.log(`DataTable with ID #${tableId} cleared.`);
        // }
        // if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
        //   dataTableRef.current.fnDestroy();
        // // $(`#${tableId}`).DataTable().clear().draw();
        // // $(`#${tableId}`).DataTable().destroy();   
        // } 
        if(tableData?.length > 0){
          // const dt =
        dataTableRef.current =  new DataTable(`#${tableId}`, {
        // $(`#${tableId}`).DataTable({
            // pagingType: 'full_numbers',
            // pageLength: 10,
            paging: false,
            info: false,
            processing: true,
            responsive: true,
            // destroy: true,
            retrieve: true,
            dom: 'Bfrtip',
            // buttons: ['copyHtml5', 'csvHtml5', 'excelHtml5', 'pdfHtml5', 'print'],
            orientation: tableData[0] && tableData[0].length > 4 ? 'landscape' : 'portrait', // Set orientation based on column count
            pageSize: tableData[0] && tableData[0].length > 4 ? 'A3' : 'A4', // Adjust page size based on the number of columns
            buttons: [
                // {
                //     extend: 'copyHtml5',
                //     exportOptions: {
                //       columns: ':visible', 
                //       modifier: {
                //         page: 'all'
                //       },
                //       format: {
                //           body: (data, row, column, node) => {
                //           // Dynamically handle the Status column
                //               if ($(node).closest('td').hasClass('status-column')) {
                //               return $(data).find('input').is(':checked') ? 'True' : 'False';
                //               }
                //               return $(node).text().trim();
                //           }
                //       },
                //       stripHtml: true,
                //     },                  
                // },
                {
                extend: 'csvHtml5',
                exportOptions: {
                    columns: ':visible',     
                    modifier: {
                    page: 'all'
                    },
                    format: {
                      body: (data, row, column, node) => {
                      // Dynamically handle the Status column
                        if ($(node).closest('td').hasClass('status-column')) {
                        return $(data).find('input').is(':checked') ? 'True' : 'False';
                        }
                        return $(node).text().trim();
                      }
                    },
                    stripHtml: true,
                }
                },
                // {
                //   extend: 'excelHtml5',
                //   exportOptions: {
                //     columns: ':visible',
                //     modifier: {
                //       page: 'all'
                //     },
                //     format: {
                //       body: (data, row, column, node) => {
                //       // Dynamically handle the Status column
                //         if ($(node).closest('td').hasClass('status-column')) {
                //         return $(data).find('input').is(':checked') ? 'True' : 'False';
                //         }
                //         return $(node).text().trim();
                //       }
                //     },
                //     stripHtml: true,
                //   }
                // },
                {
                  extend: 'pdf',
                  exportOptions: {
                    columns: ':visible', 
                    stripHtml: false,
                    modifier: {
                      page: 'all'
                    }
                  },
                  action: ( e, dt, button, config ) => {
                    // const table = dt.table().node(); // Get table node

                    // // Use html2canvas and jsPDF to create the PDF
                    // html2canvas(table, {
                    //     scale: 2, // Higher scale increases resolution
                    //     allowTaint:true,
                    //     useCORS: true,
                    // }).then((canvas) => {
                    //     const pdf = new JsPDF('p', 'mm', 'a4'); // Portrait orientation
                    //     const imgData = canvas.toDataURL('image/png');
                    //     const pdfWidth = pdf.internal.pageSize.getWidth();
                    //     const pdfHeight = (canvas.height * pdfWidth) / canvas.width;

                    //     pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
                    //     pdf.save('table.pdf'); // Saves the PDF with the specified name
                    // });

                    const table = document.getElementById(tableId)
                    
                    const opt = {
                      margin: [15,15],
                      filename: 'table.pdf',
                      image:        { type: 'jpeg', quality: 0.98 },
                      html2canvas:  { scale: 2, letterRendering: true },
                      jsPDF:        { unit: 'pt', format: 'letter', orientation: 'portrait' },
                     pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
                   };
                    html2pdf().from(table).set(opt).save()
                  }
                },
                {
                    extend: 'print',
                    exportOptions: {
                      columns: ':visible', 
                      stripHtml: false,
                      modifier: {
                        page: 'all'
                      }
                    }
                  },
                'colvis',

              ],
              initComplete: ()=> {
                // $(`#${tableId}`).addClass('table table-bordered table-hover toggle-circle custom-table table');
            }
            });
            console.log(`DataTable with ID #${tableId} initialized.`);
            // if (dataTableRef.current) {
            //   console.log(2)
            //   dataTableRef.current.clear()//.destroy(true);
            //   dataTableRef.current = null;
            // }
        // Cleanup function to destroy the DataTable when component unmounts
        // return () => {
        // $(`#${tableId}`).DataTable().destroy(true);
        // console.log(`DataTable with ID #${tableId} cleaned up on unmount.1`);
        // };
    }
    // return () => {
    //   if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
    //     $(`#${tableId}`).DataTable().clear().draw(false);
    //     console.log(`DataTable with ID #${tableId} cleaned up on unmount.2`);
    //   }
    // };
    // return null
    // if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
    //   $(`#${tableId}`).DataTable().destroy(false);
    // }

  }, [tableId, tableData]);


//   return null; // No need to render anything
};

export default MasterDataTable;

Problem is that when i add an item to the datatable, and then print, then the added item is not seen in the table in print. and if i delete an item from the table then it disappears. But in the print view, the item can still be seen. To simplify, the print view is not showing the updated datatable but an old one. Ofcourse when i refresh the page then everything works fine but that is not a solution. any help would be much appreciated. Thanks in advance.

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Are you using Editor to update the table? Or are you using the DataTables API or just editing the HTML directly? If you're editing the HTML directly, then DataTables wouldn't know about that change, so this behaviour would be expected. Can you clarify what you're doing, please.

    Colin

  • waqaranwar2021waqaranwar2021 Posts: 16Questions: 3Answers: 0
    edited October 30

    Thanks for your reply Colin, yes i am editing the HTML directly. Any workarounds for this to work? the CSV and PDF are working fine with updated data. can't tell why only print is not working fine.

  • waqaranwar2021waqaranwar2021 Posts: 16Questions: 3Answers: 0

    Edit: sorting and searching also includes past data not updated data. any way to handle all these scenarios (perhaps proper destruction and re-initialization of datatable)?

  • kthorngrenkthorngren Posts: 21,374Questions: 26Answers: 4,957

    See this FAQ about how to make updates that Datatables knows about.

    Kevin

  • waqaranwar2021waqaranwar2021 Posts: 16Questions: 3Answers: 0

    Thanks for your reply Kevin, i have tried rows().invalidate() and destroying, then re-initializing the datatable multiple times but no luck.

  • kthorngrenkthorngren Posts: 21,374Questions: 26Answers: 4,957
    edited October 30

    The invalidate methods, like rows().invalidate(), only work with cells that have been updated. The docs state this:

    DataTables holds cached information about the contents of each cell in the table

    This method can be used to tell DataTables to re-read the information from the data source for the row (be it from the DOM or objects / arrays - whatever the original data source was).

    This means that Datatables won't know about new rows added directly to the DOM. It also means that rows removed directly from the DOM aren't removed from the cache and thus remain when row().invalidate() is used.

    The best option is to use row.add() to add a new row and row().remove() to remove a row. See this example to learn how to get the row to be used with the Datatables API.

    Kevin

Sign In or Register to comment.