Tengo una tabla que muestra datos de una api y permite el típico CRUD.
A la hora de borrar por id, cuando se presiona el botón de borrado se abre un modal para confirmar la acción; desde el modal llamo a la función que elimina los datos seleccionados.
El problema es que desde el modal no borra la fila deseada, borra la ultima añadida en la api, si lo hago directamente, saltándome el modal si que se borra la fila que yo deseo. Como puedo hacer que el modal sepa el id de la fila que deseo eliminar?
export const TableGuide = () => {
const [guideList, setGuideList] = useState<Guide[]>([]);
const [isLoading, setIsLoadind] = useState(false)
const [showModalDelete, setShowModalDelete] = useState(false)
const [showModalEdit, setShowModalEdit] = useState(false)
const [currentPageGuide, setCurrentPageGuide] = useState(0);
const [viewMoreGuideDataDisabled, setViewMoreGuideDataDisabled] = useState(false);
const openModalDelete = () => setShowModalDelete(true);
const closeModalDelete = () => setShowModalDelete(false);
const openModalEdit = () => setShowModalEdit(true);
const closeModalEdit = () => setShowModalEdit(false);
const [aceptar, setAceptar] = useState(false)
const fetchGuideList = async () => {
setIsLoadind(true)
getGuide().then((response)=>{
console.log(response)
setGuideList(response);
setIsLoadind(false)
var filter = {
page: 0,
};
fetchGuidePaginated(filter)
}).catch ( (error) => {
console.error(error);
throw error;
});
}
const fetchGuidePaginated = async (filter) => {
getGuidePaginated(filter)
.then((response)=>{
console.log(`response.length: ${response.length}`);
if (response.length > getItemsPerPage()) {
response.pop();
setViewMoreGuideDataDisabled(false);
} else {
setViewMoreGuideDataDisabled(true);
}
var list:Guide[] = [];
if (filter.page == 0) {
list = response;
} else {
list = [...guideList, ...response];
}
setGuideList(list);
console.log(list);
}).catch((error) => {
console.error(error);
throw error;
});
}
const handleShowMoreData = () => {
setCurrentPageGuide(currentPageGuide + 1);
var filter = {
page: currentPageGuide + 1,
};
fetchGuidePaginated(filter);
}
useEffect (() => {
fetchGuideList();
}, []);
return(
<>
<table>
<thead>
<tr>
<th className="text-xs text-neutral-800">Fecha creación</th>
<th className="text-xs text-neutral-800">Autor</th>
<th className="text-xs text-neutral-800">Título</th>
<th className="text-xs text-neutral-800">Descripción</th>
<th className="text-xs text-neutral-800">Fecha publicación</th>
<th className="text-xs text-neutral-800">Estado</th>
<th />
</tr>
</thead>
<tbody>
{isLoading && <Loader />}
{guideList.map((guide) => (
<tr key={guide.id}>
<td data-label="creationDate" className="lg:w-32 whitespace-nowrap">
<small className="text-teal-500 dark:text-slate-400">{guide.creationDate}</small>
</td>
<td data-label="creator" className="text-xs text-neutral-800">{guide.creator}</td>
<td data-label="title" className="text-xs text-neutral-800">{guide.title}</td>
<td data-label="description" className="text-xs text-neutral-800">{guide.description}</td>
<td data-label="publishDate" className="lg:w-40 whitespace-nowrap">
<small className="text-teal-500 dark:text-slate-400">{guide.publishDate}</small>
</td>
<td data-label="enabled" className="lg:w-32 text-xs text-sky-500">{guide.enabled}</td>
<td className="before:hidden lg:w-1 whitespace-nowrap">
<div className="justify-start lg:justify-end whitespace-nowrap" >
<BaseButton icon={mdiDownloadCircleOutline} small color="tableIcofcv" className="mx-1 bg-transparent hover:bg-teal-600 text-teal-600 hover:text-white border-0"/>
<BaseButton icon={mdiLinkVariant} small color="tableIcofcv" className="mx-1 bg-transparent hover:bg-teal-600 text-teal-600 hover:text-white border-0"/>
<BaseButton onClick={openModalEdit} icon={mdiPencil} small color="tableIcofcv" className="mx-1 bg-transparent hover:bg-teal-600 text-teal-600 hover:text-white border-0"/>
<BaseButton onClick={openModalDelete} icon={mdiTrashCan} color="tableIcofcvDanger" small className="mx-1 bg-transparent hover:bg-red-500 text-red-500 hover:text-white border-0"/>
</div>
</td>
</tr>
))}
</tbody>
</table>
<div className="p-3 lg:px-6 border-t border-gray-100 dark:border-slate-800">
{viewMoreGuideDataDisabled === false ?
<div className="flex items-center justify-end mx-3">
<button className="bg-transparent text-teal-600 text-sm active:bg-teal-700 py-2 outline-none focus:outline-none rounded underline" type="button" onClick={handleShowMoreData}>Ver más</button>
</div>
:
<div></div>
}
</div>
<ModalEditGuide showModalEdit={showModalEdit} closeModalEdit={closeModalEdit } />
<ModalDeleteGuide showModalDelete={showModalDelete} closeModalDelete={closeModalDelete } />
)
}
/////modal delete
interface Props {
showModalDelete: boolean,
closeModalDelete: () => void ,
guide: Guide[]
}
export const ModalDeleteGuide: React.FC<Props> = ({ children, showModalDelete, closeModalDelete, guide }) => {
const deleteGuide = (id) => {
deleteGuidesById(id).then((response) => {
console.log(response);
}).catch((error) => {
console.error(error);
throw error;
});
}
return(
<>
{showModalDelete === true ?
<>
<div id="defaultModal" aria-hidden="true" className="fixed top-0 z-40 inset-0 bg-gray-500 bg-opacity-75 transition-opacity "></div>
<div className="fixed inset-0 z-50 overflow-y-auto ">
<div className="flex min-h-full items-end justify-center p-4 sm:items-center sm:p-0">
<CardBox className="w-full max-w-lg">
{/* Modal header */}
<div className="flex justify-between items-start py-4 rounded-t border-b dark:border-gray-600 mb-4 px-6">
<h3 className="text-xl font-semibold text-gray-900 dark:text-white">Borrar ventaja</h3>
<button type="button" className="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-600 dark:hover:text-white" data-modal-toggle="defaultModal" onClick={closeModalDelete}>
<svg aria-hidden="true" className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
</svg>
<span className="sr-only">Close modal</span>
</button>
</div>
{/* Modal body */}
<div className="p-6 space-y-6">
<div>
<p className="text-neutral-600">¿Estas seguro de eliminar esta ventaja? Si es así pulsa sobre el botón Aceptar.</p>
</div>
<BaseDivider />
<BaseButtons>
<BaseButton onClick={()=>deleteGuide(guide.id)} color="icofcv" label="Aceptar" />
<BaseButton type="reset" color="icofcv" outline onClick={closeModalDelete} label="Cancelar" />
</BaseButtons>
</div>
</CardBox>
</div>
</div>
</>
:null
}
</>
)
}
////////api
export async function deleteGuidesById(id): Promise<Guide[]> {
console.log('id:',id)
const filter = {
"offset": 0,
"limit": 500 ,
"skip": 0,
"where": {
"id": id
},
"fields": {
"id": true,
"creationDate": true,
"creator": true,
"title": true,
"description": true,
"publishDate": true,
"documentPath": true,
"imagePath": true,
"enabled": true
}
};
const response = await fetch(config.apiBaseUrl+`/guides/${id}?filter=`+encodeURIComponent(JSON.stringify(filter)), {
method: "DELETE",
headers: getHeaders()
});
const data = await response.json();
if (response.ok) {
return data;
} else {
return Promise.reject(response.status);
}
}