import React, {FC, useEffect, useState} from "react"
import useAxiosTools from "../../hooks/AxiosTools";
import {rainfall} from "../../types";
import {AxiosError} from "axios";

const LastFiveMesure: FC<LastFiveMesureProps> = ({loadedAt}) => {

    const {error, setError, axiosGet} = useAxiosTools()
    const [data, setData] = useState<rainfall[]>([])

    useEffect(() => {
        fetchData()
    }, [loadedAt])

    const fetchData = async () => {
        try {
            const res = await axiosGet('/api/rainfalls/last')
            setData(res.data)
        } catch (e) {
            if (e instanceof AxiosError) {
                setError(e.message)
            } else {
                console.error(e)
            }
        }
    }

    return <div>
        <h1>5 dernières mesures</h1>
        {error && <div>{error}</div>}
        <ul>
            {data.map(line => <li key={line.id} className="w-36 flex justify-between">
                <span>{(new Date(line.date)).toLocaleDateString()}</span>
                <span>{line.value}</span>
            </li>)}
        </ul>
    </div>
}

export default LastFiveMesure

interface LastFiveMesureProps {
    loadedAt: Date,
}
