external-knowledge-api-context.tsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use client'
  2. import { createContext, useContext, useMemo } from 'react'
  3. import type { FC, ReactNode } from 'react'
  4. import useSWR from 'swr'
  5. import type { ExternalAPIItem, ExternalAPIListResponse } from '@/models/datasets'
  6. import { fetchExternalAPIList } from '@/service/datasets'
  7. type ExternalKnowledgeApiContextType = {
  8. externalKnowledgeApiList: ExternalAPIItem[]
  9. mutateExternalKnowledgeApis: () => Promise<ExternalAPIListResponse | undefined>
  10. isLoading: boolean
  11. }
  12. const ExternalKnowledgeApiContext = createContext<ExternalKnowledgeApiContextType | undefined>(undefined)
  13. export type ExternalKnowledgeApiProviderProps = {
  14. children: ReactNode
  15. }
  16. export const ExternalKnowledgeApiProvider: FC<ExternalKnowledgeApiProviderProps> = ({ children }) => {
  17. const { data, mutate: mutateExternalKnowledgeApis, isLoading } = useSWR<ExternalAPIListResponse>(
  18. { url: '/datasets/external-knowledge-api' },
  19. fetchExternalAPIList,
  20. )
  21. const contextValue = useMemo<ExternalKnowledgeApiContextType>(() => ({
  22. externalKnowledgeApiList: data?.data || [],
  23. mutateExternalKnowledgeApis,
  24. isLoading,
  25. }), [data, mutateExternalKnowledgeApis, isLoading])
  26. return (
  27. <ExternalKnowledgeApiContext.Provider value={contextValue}>
  28. {children}
  29. </ExternalKnowledgeApiContext.Provider>
  30. )
  31. }
  32. export const useExternalKnowledgeApi = () => {
  33. const context = useContext(ExternalKnowledgeApiContext)
  34. if (context === undefined)
  35. throw new Error('useExternalKnowledgeApi must be used within a ExternalKnowledgeApiProvider')
  36. return context
  37. }