import { Query } from "expo-sqlite";
import { useEffect, useState } from "react";
import { executeQuery } from "../services/database";

const useFetch = (query: Query) => {

    const [isLoading, setIsLoading] = useState(false);
    const [data, setData] = useState<{[column: string]: any;}[]>([]);

    const reFetch = () => {

        setIsLoading(true);
        executeQuery(query).then((result) => {
            if("rows" in result[0]) {
                setData(result[0]["rows"]);
            }
        }).catch((error: any) => {
            console.error("Fetching data from database has failed: ", error);
        }).finally(() => {
            setIsLoading(false);
        });
    }

    useEffect(() => {
        reFetch();
    }, [])

    return {data, isLoading, reFetch};
}

export default useFetch;