use-root-doc-id.tsx 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { useCallback } from 'react'
  2. import { useEditorContext } from '../../../shared/context/editor-context'
  3. import useScopeValue from '../../../shared/hooks/use-scope-value'
  4. import type { ProjectSettings } from '../utils/api'
  5. import useSaveProjectSettings from './use-save-project-settings'
  6. export default function useRootDocId() {
  7. const [rootDocId] =
  8. useScopeValue<ProjectSettings['rootDocId']>('project.rootDocId')
  9. const { permissionsLevel } = useEditorContext()
  10. const saveProjectSettings = useSaveProjectSettings()
  11. const setRootDocIdFunc = useCallback(
  12. async (newRootDocId: ProjectSettings['rootDocId']) => {
  13. // rootDocId will be undefined on angular scope on initialisation
  14. const allowUpdate =
  15. typeof rootDocId !== 'undefined' && permissionsLevel !== 'readOnly'
  16. if (allowUpdate) {
  17. try {
  18. await saveProjectSettings('rootDocId', newRootDocId)
  19. } catch (err) {
  20. // TODO: retry mechanism (max 10x before failed completely and rollback the old value)
  21. }
  22. }
  23. },
  24. [permissionsLevel, rootDocId, saveProjectSettings]
  25. )
  26. return {
  27. rootDocId,
  28. setRootDocId: setRootDocIdFunc,
  29. }
  30. }