feat: frontend responding to backend SSE and refetching images
This commit is contained in:
79
frontend/src/contexts/SearchImageContext.tsx
Normal file
79
frontend/src/contexts/SearchImageContext.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
createContext,
|
||||
type Resource,
|
||||
type Component,
|
||||
type ParentProps,
|
||||
createResource,
|
||||
useContext,
|
||||
} from "solid-js";
|
||||
import { getUserImages } from "../network";
|
||||
|
||||
type ImageWithRawData = Awaited<ReturnType<typeof getUserImages>>[number] & {
|
||||
rawData: string[];
|
||||
};
|
||||
|
||||
type SearchImageStore = {
|
||||
images: Resource<ImageWithRawData[]>;
|
||||
onRefetchImages: () => void;
|
||||
};
|
||||
|
||||
// How wonderfully functional
|
||||
const getAllValues = (object: object): Array<string> => {
|
||||
const loop = (acc: Array<string>, next: object): Array<string> => {
|
||||
for (const _value of Object.values(next)) {
|
||||
const value: unknown = _value;
|
||||
switch (typeof value) {
|
||||
case "object":
|
||||
if (value != null) {
|
||||
acc.push(...loop(acc, value));
|
||||
}
|
||||
break;
|
||||
case "string":
|
||||
case "number":
|
||||
case "boolean":
|
||||
acc.push(value.toString());
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return acc;
|
||||
};
|
||||
|
||||
return loop([], object);
|
||||
};
|
||||
|
||||
const SearchImageContext = createContext<SearchImageStore>();
|
||||
export const SearchImageContextProvider: Component<ParentProps> = (props) => {
|
||||
const [images, { refetch }] = createResource(() =>
|
||||
getUserImages().then((data) => {
|
||||
return data.map((d) => ({
|
||||
...d,
|
||||
rawData: getAllValues(d),
|
||||
}));
|
||||
}),
|
||||
);
|
||||
|
||||
return (
|
||||
<SearchImageContext.Provider
|
||||
value={{
|
||||
images,
|
||||
onRefetchImages: refetch,
|
||||
}}
|
||||
>
|
||||
{props.children}
|
||||
</SearchImageContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useSearchImageContext = () => {
|
||||
const context = useContext(SearchImageContext);
|
||||
if (context == null) {
|
||||
throw new Error(
|
||||
"Unreachable: We should always have a mounted context and no undefined values",
|
||||
);
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user