use-project-entities.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { useEffect, useState } from 'react'
  2. import { getJSON } from '../../../infrastructure/fetch-json'
  3. import { fileCollator } from '../util/file-collator'
  4. import useAbortController from '../../../shared/hooks/use-abort-controller'
  5. export type Entity = {
  6. path: string
  7. }
  8. const alphabetical = (a: Entity, b: Entity) =>
  9. fileCollator.compare(a.path, b.path)
  10. export function useProjectEntities(projectId?: string) {
  11. const [loading, setLoading] = useState(false)
  12. const [data, setData] = useState<Entity[] | null>(null)
  13. const [error, setError] = useState<any>(false)
  14. const { signal } = useAbortController()
  15. useEffect(() => {
  16. if (projectId) {
  17. setLoading(true)
  18. setError(false)
  19. setData(null)
  20. getJSON(`/project/${projectId}/entities`, { signal })
  21. .then(data => {
  22. setData(data.entities.sort(alphabetical))
  23. })
  24. .catch(error => setError(error))
  25. .finally(() => setLoading(false))
  26. }
  27. }, [projectId, signal])
  28. return { loading, data, error }
  29. }