Holiday Notice: Support will be provided on a limited scale from December 24th, 2024, to January 2nd, 2025. Happy holidays and a wonderful New Year!

Bridget Melvin premium asked 2 years ago


Expected behavior delete button (cell in datatable) has onClick event handler removeRowHandler that should permanently remove the row corresponding to the array of row objects from the array (permanently)

Actual behavior The first delete/click works, but when I go to delete a second row, the first deleted row returns to the datatable... useState is not properly updating rowData nor tableData in the datatable

Resources (screenshots, code snippets etc.)

Note mdbReactUiKit is an alias for mdb-react-ui-kit

UsersTable.js

import React, { useState } from 'react';
import { Link } from 'react-router-dom';

import { MDBDatatable, MDBBtn, MDBIcon } from 'mdbReactUiKit';
import Wrapper from '../Wrapper';
import styled from 'styled-components';

import { rows, cols } from '../../variables/Users';

const TableContainer = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  width: auto;
`

const StyledTable = styled(MDBDatatable)`
  width: 80%;
`

const StyledLink = styled(Link)`
  color: inherit;
`

const StyledButton = styled(MDBBtn)`
  padding: 3px!important;
  margin: 3px!important;
`
const Table = ({ tableData }) => {
  // const [actionData, setActionData] = useState({
  //   columns: cols,
  //   rows: addCustomButtons(rows)
  // });

  return (
    <StyledTable
      hover
      striped

      data={tableData}
      advancedData
      entriesOptions={[5, 10, 20]}
      entries={10}

      fixedHeader
      maxHeight='460px'
    />
  )
}


export default function UsersTable() {
  const [rowData, setRowData] = useState(addCustomButtons(rows))

  const [tableData, setTableData] = useState({
    columns: cols,
    rows: rowData
  })

  function addCustomButtons(rows) {
    return rows.map((row, idx) => {
      return {
        ...row,
        index: idx,
        email: (
          <StyledLink
            to='#'
            onClick={(e) => {
              window.location.href = `mailto:${row.emailraw}`;
              e.preventDefault();
            }}
          >
            {row.emailraw}
          </StyledLink>
        ),
        buttons: (
          <>
            <StyledButton
              size='sm'
              floating
              className='message-btn'
              onClick={() => console.log(`send a message to ${row.emailraw}`)}
            >
              <MDBIcon icon='envelope' />
            </StyledButton>
            <StyledButton outline size='sm' floating className='call-btn' onClick={() => console.log(`edit user settings`)}>
              <MDBIcon icon='arrow-right' />
            </StyledButton>
            <StyledButton
              size='sm'
              floating
              className='remove-user-btn'
              onClick={(event) => removeRowHandler(idx, event)}
            >
              <MDBIcon icon="trash" />
            </StyledButton>
          </>
        ),
      };
    })
  }


  const removeRowHandler = (index, event) => {
    if (rowData.length > 1) {
      var updatedRows = [...rowData]
      var indexToRemove = updatedRows.findIndex(x => x.index === index)

      if (indexToRemove > -1) {
        var newRows = [
          ...updatedRows.slice(0, indexToRemove),
          ...updatedRows.slice(indexToRemove + 1, updatedRows.length)
        ]

        setRowData(newRows)
        setTableData({
          columns: cols,
          rows: newRows
        })
      }
    }
  }

  console.log('rowData', rowData)

  const deleteRow = (index, event) => {
    if (rowData.length > 1) {
      var updatedRows = [...rowData]
      console.log('1st rowData', updatedRows)

      var indexToRemove = updatedRows.findIndex(x => x.index === index)
      console.log('remove', indexToRemove, index)

      if (indexToRemove > -1) {
        updatedRows.splice(indexToRemove, 1)
        var newRows = addCustomButtons(updatedRows)

        console.log(updatedRows, newRows)
        setRowData(newRows)
        setTableData({
          columns: cols,
          rows: newRows
        })
      }
    }
  }


  return (
    <Wrapper>
      <TableContainer>
        <Table tableData={tableData} />
      </TableContainer>
    </Wrapper>
  );
}

Users.js

export const rows = [
  {
    name: 'Jennifer Doe',
    emailraw: 'jennifer.doe@rockequity.com',
    role: 'Admin',
  },
  {
    name: 'Ryan Tse',
    emailraw: 'ryan.tse@rockequity.com',
    role: 'Collaborator',
  },
  {
    name: 'Jane Rach',
    emailraw: 'jane.rach@rockequity.com',
    role: 'User',
  },
  {
    name: 'Eric Eay',
    emailraw: 'eric@cpa-QofE.com',
    role: 'User',
  },
  {
    name: 'Jack Plence',
    emailraw: 'jack@fastserv.com',
    role: 'Collaborator',
  },
  {
    name: 'Tiger Nixon',
    emailraw: 'tiger.nixon@gmail.com',
    role: 'External User',
  },
  {
    name: 'Sonya Frost',
    emailraw: 'sfrost@gmail.com',
    role: 'External User',
  },
  {
    name: 'Tatyana Fitzpatrick',
    emailraw: 'tfitz@gmail.com',
    role: 'External User',
  },
]

export const cols = [
  { label: 'Name', field: 'name' },
  { label: 'Email', field: 'email' },
  { label: 'Role', field: 'role' },
  { label: 'Actions', field: 'buttons', sort: false },
]


MDBDatatable was designed to present the data, not to edit them. If you want to edit your data, you could use MDBTableEditor. Anyway, Datatable works fine in this case, the problem is probably with your delete mechanism (you are passing function copies and the rowData is not being refreshed as you want to).



We have released new Datatables just yesterday. You should try to update your package and use the newer MDBDatatable.


Bridget Melvin premium commented 2 years ago

I am using React17 therefore the version 3.0.0 -- is it not possible with this version?


Wojciech Staniszewski staff commented 2 years ago

It should not be a problem. If there will be, you should try to migrate your project to React 18 version. We cannot provide support and updates for deprecated components.


Bridget Melvin premium commented 2 years ago

I migrated the project to React 18 and the problem persists



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Premium
  • Premium support: Yes
  • Technology: MDB React
  • MDB Version: MDB5 3.0.0
  • Device: Surface Laptop Studio
  • Browser: Chrome
  • OS: Windows 11
  • Provided sample code: Yes
  • Provided link: No