skip to Main Content

I have this code to delete row from table of clients:

const [clients, setClients] = useState([]);

  const deleteRow = (without) => {
        console.log("BEFORE ", ...clients.map(client => client.userId));
        let filtered = clients.filter((client) => client.userId !== without);
        setClients(filtered);
        //console.log("DELETE ", ...filtered.map(client => client.userId));
    }

    useEffect(() => {
        if (clients === null) return;
        console.log("UPDATE ", ...clients.map(client => client.userId));
     }, [clients]); // clients is dependency

When I delete two I get following result.

output:

UPDATE  151 146 145 96
BEFORE  151 146 145 96
UPDATE  151 145 96
BEFORE  151 146 145 96

Why for the second time clients are the same as at first?

Edit 1.
I use

<BootstrapTable striped keyField="id" data={clients} remote={{ pagination: true }}
onTableChange={() => { }}
columns={getClientsColumn(deleteRow, setBool)}
/>

and when I delete from colum with delete button it get wrong BUT when I do the same operation outside this bootstrap table every thing is ok

<ButtonGroup size="sm">
<Button variant="danger" onClick={() => deleteRow(clients[1].userId)} >Delete 1</Button>
<Button variant="danger" onClick={() => deleteRow(clients[0].userId)} >Delete 2</Button>
</ButtonGroup>

2

Answers


  1. Chosen as BEST ANSWER

    OK I found the solution.

    I need to pass the clients and setClient to the Context and get that values inside the code responsible for deleting the client in column.


  2. Try using a functional state update instead:

    const deleteRow = (without) => {
      setClients(prevClients => {
        console.log("BEFORE ", ...prevClients.map(client => client.userId));
        let filtered = prevClients.filter(client => client.userId !== without);
        return filtered;
      });
    }
    

    This will ensure the state updates with the latest value.

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