-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: moved fetch-production-list into a separate hook
- Loading branch information
1 parent
48fcd4e
commit 387e0bf
Showing
2 changed files
with
62 additions
and
47 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
import { useEffect, useState } from "react"; | ||
import { useGlobalState } from "../../global-state/context-provider"; | ||
import { API } from "../../api/api.ts"; | ||
import { TBasicProduction } from "../production-line/types.ts"; | ||
|
||
export const useFetchProductionList = () => { | ||
const [productions, setProductions] = useState<TBasicProduction[]>([]); | ||
const [doInitialLoad, setDoInitialLoad] = useState(true); | ||
const [intervalLoad, setIntervalLoad] = useState<boolean>(false); | ||
const [error, setError] = useState<Error | null>(null); | ||
|
||
const [{ reloadProductionList }, dispatch] = useGlobalState(); | ||
|
||
useEffect(() => { | ||
let aborted = false; | ||
|
||
if (reloadProductionList || intervalLoad || doInitialLoad) { | ||
API.listProductions() | ||
.then((result) => { | ||
if (aborted) return; | ||
|
||
setProductions( | ||
result | ||
// pick laste 10 items | ||
.slice(-10) | ||
); | ||
|
||
dispatch({ | ||
type: "PRODUCTION_LIST_FETCHED", | ||
}); | ||
|
||
setIntervalLoad(false); | ||
setDoInitialLoad(false); | ||
setError(null); | ||
}) | ||
.catch((e) => { | ||
setError( | ||
e instanceof Error | ||
? e | ||
: new Error("Failed to fetch production list.") | ||
); | ||
}); | ||
} | ||
|
||
return () => { | ||
aborted = true; | ||
}; | ||
}, [dispatch, intervalLoad, reloadProductionList, doInitialLoad]); | ||
|
||
return { | ||
productions, | ||
doInitialLoad, | ||
error, | ||
setIntervalLoad, | ||
}; | ||
}; |