skip to Main Content

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;

3

Answers


  1. Chosen as BEST ANSWER

    how i solved this problem,

      const [datos, setDatos] = React.useState(React.useMemo(() => data, []));
    

    i had to use useEffect

    useEffect(() => {
        setDatos(data);
      }, [data]);
    

  2. 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.

    Login or Signup to reply.
  3. There are a few options
    You can either re-fetch the "resourceData" using your API method after the deletion. Which requires another API call

    Or update the delete method to remove the data from the list.

    If you want to use the second option I’d recommend using useState to manage the state of the resourceData

    Something like

    const {resourceData, setResourceData} = useState(data)

    and in the delete method

    setResourceData(resourceData.filter(record => record.id != id))

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search