javascriptreactjsreact-hooksreact-table-v7

why do i have to refresh the page when i delete a row?


i'm doing the delete row option for my table with data of a api and the delete request works well but i have to refresh the page to update my rows do you know why and what can i do ? i'm using react-table-v7

const useTableResource = () => {
  const {data} = apiData();
  const resourcesData = data;
  
  const resourcesDataLength = resourcesData.length;
  const query = window.matchMedia('(max-width: 750px)');
 

  const resourcesColumns = useMemo(() => [
    {Header: 'Tittle', accessor: 'name'},
    {
      id: 'delete',
      accessor: () => 'delete',
      disableSortBy: true,
      Cell: ({row}) => <div onClick={(event) => event.stopPropagation()} style={{
        display: 'flex',
        justifyContent: 'center'
      }}>
        <DeleteModal delb={async () => {
          await axios.delete(`api/resources?_id=${row.original._id}`);
        }}/>

      </div>

    }
  ], []);


  const tableInstance = useTable({
    columns: resourcesColumns,
    data: resourcesData, //here load the data for my table
    disableSortRemove: true,
    initialState: {
      sortBy: [{id: 'resourceType.name', desc: false}],
      pageSize: 10
    }
  }, useSortBy, usePagination);


  return {
    tableInstance,
    resourcesColumns,
    resourcesDataLength
  };
};

export default useTableResource;

Solution

  • I have to refresh the page to update my rows

    It's because, you are not updating your resourceData based on the operation you do. And react re-renders the component if there is any change made to the state (resourceData).

    How can I tell react to re-render the component ?

    One way is to make the apiData() call again after the successful delete operation and update your resourceData state or if you feel, api operation is costly, then alter your resourceData state to remove the deleted element.