Source

adminjs/src/frontend/hooks/use-current-admin.ts

  1. import { useDispatch, useSelector } from 'react-redux'
  2. import { ReduxState } from '../store/store'
  3. import { setCurrentAdmin } from '../store/actions/set-current-admin'
  4. import { CurrentAdmin } from '../../current-admin.interface'
  5. export type UseCurrentAdminResponse = [
  6. CurrentAdmin | null,
  7. (currentAdmin: CurrentAdmin | null) => CurrentAdmin | {}
  8. ]
  9. /**
  10. * @classdesc
  11. * Hook which allows you to get and set currentAdmin
  12. *
  13. * ### Usage
  14. *
  15. * ```javascript
  16. * import { useCurrentAdmin } from 'adminjs'
  17. *
  18. * const myComponent = () => {
  19. * const [currentAdmin, setCurrentAdmin] = useCurrentAdmin()
  20. * // ...
  21. * }
  22. * ```
  23. *
  24. * @class
  25. * @subcategory Hooks
  26. * @bundle
  27. * @returns {UseCurrentAdminResponse}
  28. * @hideconstructor
  29. */
  30. function useCurrentAdmin(): UseCurrentAdminResponse {
  31. const currentAdmin = useSelector((state: ReduxState) => state.session)
  32. const dispatch = useDispatch()
  33. return [
  34. currentAdmin,
  35. (admin: CurrentAdmin | null): any => dispatch(setCurrentAdmin(admin)),
  36. ]
  37. }
  38. export {
  39. useCurrentAdmin,
  40. useCurrentAdmin as default,
  41. }
  42. /**
  43. * Result of the {@link useCurrentAdmin}.
  44. * It is a tuple containing value and the setter
  45. *
  46. * @typedef {Array} UseCurrentAdminResponse
  47. * @memberof useCurrentAdmin
  48. * @alias UseCurrentAdminResponse
  49. * @property {CurrentAdmin | null} [0] current admin
  50. * @property {React.Dispatch<React.SetStateAction<CurrentAdmin>>} [1] value setter compatible
  51. * with react useState
  52. */