This repository has been archived on 2026-04-20. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
interaktive-systeme/hooks/useFetch.ts

55 lines
No EOL
1.5 KiB
TypeScript

import { Query } from "expo-sqlite";
import { useEffect, useState } from "react";
import { executeQuery } from "../services/database";
const useFetch = (query: Query) => {
const [fetchState, setFetchState] = useState<{
data: {[column: string]: any;}[];
isLoading: boolean;
isEmptyResult: boolean | undefined;
}>({
data: [],
isLoading: false,
isEmptyResult: undefined
});
const setIsLoading = (isLoading: boolean) => {
setFetchState((prevState) => ( {...prevState, isLoading} ));
}
const setData = (data: {[column: string]: any;}[]) => {
setFetchState((prevState) => ( {...prevState, data} ));
}
const setIsEmptyResult = (isEmptyResult: boolean) => {
setFetchState((prevState) => ( {...prevState, isEmptyResult} ));
}
const reFetch = () => {
console.log("refetch called")
setIsLoading(true);
executeQuery(query).then((result) => {
if("rows" in result[0]) {
setData(result[0]["rows"]);
if(result[0]["rows"].length == 0){
setIsEmptyResult(true);
}
console.log("len", result[0]["rows"].length)
}
}).catch((error: any) => {
console.error("Fetching data from database has failed: ", error);
}).then(() => {
setIsLoading(false);
});
}
useEffect(() => {
reFetch();
}, [])
return {...fetchState, reFetch};
}
export default useFetch;