| 1 |
import React, { useCallback, useEffect, useState } from 'react' |
| 2 |
import { createContextHook } from '../utils/hooks' |
| 3 |
import { isNetworkAdmin } from '../utils/screen' |
| 4 |
import { useRestAPI } from './useRestAPI' |
| 5 |
import type { PropsWithChildren } from 'react' |
| 6 |
import type { Snippet } from '../types/Snippet' |
| 7 |
|
| 8 |
export interface SnippetsListContext { |
| 9 |
snippetsList: readonly Snippet[] | undefined |
| 10 |
refreshSnippetsList: () => Promise<void> |
| 11 |
} |
| 12 |
|
| 13 |
const [SnippetsListContext, useSnippetsList] = createContextHook<SnippetsListContext>('SnippetsList') |
| 14 |
|
| 15 |
export const WithSnippetsListContext: React.FC<PropsWithChildren> = ({ children }) => { |
| 16 |
const { snippetsAPI: { fetchAll } } = useRestAPI() |
| 17 |
const [snippetsList, setSnippetsList] = useState<Snippet[]>() |
| 18 |
|
| 19 |
const refreshSnippetsList = useCallback(async (): Promise<void> => { |
| 20 |
try { |
| 21 |
console.info('Fetching snippets list') |
| 22 |
const response = await fetchAll(isNetworkAdmin()) |
| 23 |
setSnippetsList(response) |
| 24 |
} catch (error: unknown) { |
| 25 |
console.error('Error fetching snippets list', error) |
| 26 |
} |
| 27 |
}, [fetchAll]) |
| 28 |
|
| 29 |
useEffect(() => { |
| 30 |
refreshSnippetsList() |
| 31 |
.catch(() => undefined) |
| 32 |
}, [refreshSnippetsList]) |
| 33 |
|
| 34 |
const value: SnippetsListContext = { |
| 35 |
snippetsList, |
| 36 |
refreshSnippetsList |
| 37 |
} |
| 38 |
|
| 39 |
return <SnippetsListContext.Provider value={value}>{children}</SnippetsListContext.Provider> |
| 40 |
} |
| 41 |
|
| 42 |
export { useSnippetsList } |
| 43 |
|