workspace-context.tsx 842 B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use client'
  2. import { createContext, useContext } from 'use-context-selector'
  3. import useSWR from 'swr'
  4. import { fetchWorkspaces } from '@/service/common'
  5. import type { IWorkspace } from '@/models/common'
  6. export type WorkspacesContextValue = {
  7. workspaces: IWorkspace[]
  8. }
  9. const WorkspacesContext = createContext<WorkspacesContextValue>({
  10. workspaces: [],
  11. })
  12. type IWorkspaceProviderProps = {
  13. children: React.ReactNode
  14. }
  15. export const WorkspaceProvider = ({
  16. children,
  17. }: IWorkspaceProviderProps) => {
  18. const { data } = useSWR({ url: '/workspaces' }, fetchWorkspaces)
  19. return (
  20. <WorkspacesContext.Provider value={{
  21. workspaces: data?.workspaces || [],
  22. }}>
  23. {children}
  24. </WorkspacesContext.Provider>
  25. )
  26. }
  27. export const useWorkspacesContext = () => useContext(WorkspacesContext)
  28. export default WorkspacesContext