PluginProbe
Code Snippets / 3.10.2
Code Snippets v3.10.2
4.0.0-beta.2 3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 All 65 releases
code-snippets / js / hooks / useSnippetsList.tsx

useSnippetsList.tsx in Code Snippets 3.10.2, at js/hooks/useSnippetsList.tsx

46 lines 1.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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