Skip to content

Instantly share code, notes, and snippets.

@prumand
Created January 17, 2024 17:37
Show Gist options
  • Save prumand/2315cf0be7817265f41e0e1e5c1c67b5 to your computer and use it in GitHub Desktop.
Save prumand/2315cf0be7817265f41e0e1e5c1c67b5 to your computer and use it in GitHub Desktop.
Making my head hurt
import { createContext, useContext } from 'react';
import { MessagesContext } from '../messages/MessagesContext';
import { getDataFromMessage } from '../messages/messenger';
type DbContextValue = {
getContexts: () => Promise<{
name: string,
active: boolean
}[]>
};
export const DbContext = createContext<DbContextValue>(null!);
export function DbProvider({ children }: { children: React.ReactNode }) {
const { subscribe } = useContext(MessagesContext);
const initialContextValue: DbContextValue = {
getContexts: async () => {
const uuid = crypto.randomUUID();
let promiseReject: (reason?: string) => void = null!;
let unsubscribe: () => void = null!;
// TODO: we're polluting here if not sub event is fired. Maybe introduce setTimeout
const setupSub = new Promise<string[]>((resolve, reject) => {
promiseReject = reject;
unsubscribe = subscribe(uuid, (response) => {
if (response[0] !== 'DB_GET') {
console.error('DB_GET failed message type', response);
unsubscribe();
reject('DB_GET failed')
}
const contexts = response.slice(1);
resolve(contexts)
});
});
try {
await getDataFromMessage(
'DB_GET',
{
uuid,
model: 'Context',
}
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e : Error | any) {
unsubscribe();
promiseReject(e.message);
}
const contextsResult = await setupSub;
return contextsResult.reduce((acc, context, idx) => {
acc.push({
name: context,
active: !!contextsResult[idx+1],
});
return acc;
}, [] as {
name: string;
active: boolean;
}[]);
}
};
return (
<DbContext.Provider value={initialContextValue}>
{children}
</DbContext.Provider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment