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