Files
lara-bermite/resources/js/pages/Rainfall/RainfallIndex.tsx
2023-09-24 16:13:28 +02:00

72 lines
2.2 KiB
TypeScript

import React, {useEffect, useState} from "react";
import PageLayout from "../../components/PageLayout";
import useAxiosTools from "../../hooks/AxiosTools";
import {rainfall} from "../../types";
const RainfallIndex = () => {
const [page, setPage] = useState(1)
const [lastPage, setLastPage] = useState(1)
const [rainfalls, setRainfalls] = useState<rainfall[]>([])
const {errorCatch, errorLabel, axiosGet, axiosDelete} = useAxiosTools()
useEffect(() => {
fetchMesures()
}, [page])
const fetchMesures = async () => {
try {
const res = await axiosGet(`/api/rainfalls?page=${page}`)
setLastPage(res.data.meta.last_page)
setRainfalls([...rainfalls, ...res.data.data])
} catch (error) {
errorCatch(error)
}
}
const handleEdit = (rainfall: rainfall) => {
console.log(rainfall)
}
const handleDelete = async (rainfall: rainfall) => {
try {
const res = await axiosDelete(`/api/rainfalls/${rainfall.id}`)
setRainfalls(rainfalls.filter(r => r.id !== rainfall.id))
} catch (error) {
errorCatch(error)
}
}
return <PageLayout>
{errorLabel()}
<table className="border w-96 text-center mx-auto">
<thead>
<tr>
<th>Date</th>
<th>Mesure</th>
<th>Actions</th>
</tr>
</thead>
<tbody className="border">
{rainfalls.map(rainfall => <tr key={rainfall.id}>
<td>{(new Date(rainfall.date)).toLocaleDateString()}</td>
<td className="px-2 text-right">{rainfall.value}</td>
<td>
{/*<button type="button" onClick={() => handleEdit(rainfall)}>Editer</button>*/}
<button type="button" onClick={() => handleDelete(rainfall)}>Supprimer</button>
</td>
</tr>)}
</tbody>
<tfoot>
<tr>
<td>
{page < lastPage && <button type="button" onClick={() => setPage(page + 1)}>Plus</button>}
</td>
</tr>
</tfoot>
</table>
</PageLayout>
}
export default RainfallIndex