mirror of
https://github.com/wgh136/nysoure.git
synced 2025-09-27 12:17:24 +00:00
add AppContext for state management and update ResourcesView to utilize context
This commit is contained in:
19
frontend/src/components/AppContext.tsx
Normal file
19
frontend/src/components/AppContext.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import {createContext, ReactNode, useContext} from "react";
|
||||
|
||||
export default function AppContext({
|
||||
children,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<context.Provider value={new Map<string, any>()}>
|
||||
{children}
|
||||
</context.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
const context = createContext<Map<string, any>>(new Map<string, any>());
|
||||
|
||||
export function useAppContext() {
|
||||
return useContext(context)
|
||||
}
|
@@ -4,12 +4,38 @@ import showToast from "./toast.ts";
|
||||
import ResourceCard from "./resource_card.tsx";
|
||||
import {Masonry, useInfiniteLoader} from "masonic";
|
||||
import Loading from "./loading.tsx";
|
||||
import {useAppContext} from "./AppContext.tsx";
|
||||
|
||||
export default function ResourcesView({loader}: {loader: (page: number) => Promise<PageResponse<Resource>>}) {
|
||||
export default function ResourcesView({loader, storageKey}: {loader: (page: number) => Promise<PageResponse<Resource>>, storageKey?: string}) {
|
||||
const [data, setData] = useState<Resource[]>([])
|
||||
const pageRef = useRef(1)
|
||||
const totalPagesRef = useRef(1)
|
||||
const isLoadingRef = useRef(false)
|
||||
|
||||
const appContext = useAppContext()
|
||||
|
||||
useEffect(() => {
|
||||
if (storageKey) {
|
||||
const data = appContext.get(storageKey + "/data")
|
||||
const page = appContext.get(storageKey + "/page")
|
||||
const totalPages = appContext.get(storageKey + "/totalPages")
|
||||
console.log("loading data", data, page, totalPages)
|
||||
if (data) {
|
||||
setData(data)
|
||||
pageRef.current = page
|
||||
totalPagesRef.current = totalPages
|
||||
}
|
||||
}
|
||||
}, [appContext, storageKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (storageKey && data.length > 0) {
|
||||
console.log("storing data", data)
|
||||
appContext.set(storageKey + "/data", data)
|
||||
appContext.set(storageKey + "/page", pageRef.current)
|
||||
appContext.set(storageKey + "/totalPages", totalPagesRef.current)
|
||||
}
|
||||
}, [appContext, data, storageKey]);
|
||||
|
||||
const loadPage = useCallback(async () => {
|
||||
if (pageRef.current > totalPagesRef.current) return
|
||||
|
Reference in New Issue
Block a user