I’m developing a web app using React where I have a table that displays a list of clients. The table should update automatically after performing CRUD operations on the clients. However, I’m encountering a specific issue: after adding or deleting a client, the table doesn’t update automatically. It only works correctly when I edit an existing client. To make the other methods work, I have to leave the page and come back to the section.
As I mentioned, the request reaches the API and returns the expected information, but updating the table fails, even though the method is theoretically implemented.
This is my code:
const loadClients = async () => {
try {
const clientsData = await salesApi.getClients();
const sortedClients = clientsData.sort((a, b) => a.id - b.id);
setClients(sortedClients);
} catch (error) {
console.error('Error fetching clients:', error);
}
};
const handleEditClick = (client) => {
setEditingClient(client);
};
const handleCancelEdit = () => {
setEditingClient(null);
};
const handleClientSubmit = async (formData) => {
try {
await salesApi.addClient({
firstName: formData.firstName,
secondName: formData.secondName,
firstLastName: formData.firstLastName,
secondLastName: formData.secondLastName,
identificationNumber: formData.identificationNumber,
isCreditCandidate: formData.isCreditCandidate,
});
console.log('Client successfully registered:', formData);
loadClients();
} catch (error) {
console.error('Error adding client:', error.message);
}
};
const handleSaveEdit = async (editedClient) => {
try {
console.log('Data to send to server:', editedClient);
await salesApi.updateClient(editedClient);
console.log('Client successfully updated:', editedClient);
loadClients();
} catch (error) {
console.error('Error updating client:', error);
}
};
const handleDeleteClient = async (clientId) => {
try {
console.log('Attempting to delete client with ID:', clientId);
const response = await salesApi.deleteClient(clientId);
console.log('Delete response:', response);
if (response.status === 200) {
console.log('Client successfully deleted:', clientId);
loadClients();
} else {
console.error('Error deleting client:', response.statusText);
}
} catch (error) {
console.error('Error deleting client:', error);
}
};
return (
<MainPageContainer>
<h1>Clients</h1>
{(editingClient || !editingClient) && (
<ClientsRegistration
onSubmit={(formData) => {
if (editingClient) {
handleSaveEdit({ ...editingClient, ...formData });
} else {
handleClientSubmit(formData);
}
}}
onCancel={handleCancelEdit}
/>
)}
<ClientsTable
clients={clients}
onEditClick={handleEditClick}
onDeleteClick={handleDeleteClient}
handleSaveEdit={handleSaveEdit}
/>
</MainPageContainer>
);
};
Any advice or help on how to approach this issue would be greatly appreciated.