53 lines
No EOL
1.4 KiB
TypeScript
53 lines
No EOL
1.4 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 = () => {
|
|
setIsLoading(true);
|
|
executeQuery(query).then((result) => {
|
|
if("rows" in result[0]) {
|
|
setData(result[0]["rows"]);
|
|
if(result[0]["rows"].length == 0){
|
|
setIsEmptyResult(true);
|
|
}
|
|
}
|
|
}).catch((error: any) => {
|
|
console.error("Fetching data from database has failed: ", error);
|
|
}).then(() => {
|
|
setIsLoading(false);
|
|
});
|
|
}
|
|
|
|
useEffect(() => {
|
|
reFetch();
|
|
}, [])
|
|
|
|
return {...fetchState, reFetch};
|
|
}
|
|
|
|
export default useFetch; |