use-remind-me-later.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { useState, useCallback, useEffect } from 'react'
  2. import customLocalStorage from '@/infrastructure/local-storage'
  3. import usePersistedState from '@/shared/hooks/use-persisted-state'
  4. /**
  5. * @typedef {Object} RemindMeLater
  6. * @property {boolean} stillDissmissed - whether the user has dismissed the notification, or if the notification is still withing the 1 day reminder period
  7. * @property {function} remindThemLater - saves that the user has dismissed the notification for 1 day in local storage
  8. * @property {function} saveDismissed - saves that the user has dismissed the notification in local storage
  9. */
  10. /**
  11. *
  12. * @param {string} key the unique key used to keep track of what popup is currently being shown (usually the component name)
  13. * @param {string} notificationLocation what page the notification originates from (eg, the editor page, project page, etc)
  14. * @returns {RemindMeLater} an object containing whether the notification is still dismissed, and functions to remind the user later or save that they have dismissed the notification
  15. */
  16. export default function useRemindMeLater(
  17. key: string,
  18. notificationLocation: string = 'editor'
  19. ) {
  20. const [dismissedUntil, setDismissedUntil] = usePersistedState<
  21. Date | undefined
  22. >(`${notificationLocation}.has_dismissed_${key}_until`)
  23. const [stillDissmissed, setStillDismissed] = useState(true)
  24. useEffect(() => {
  25. const alertDismissed = customLocalStorage.getItem(
  26. `${notificationLocation}.has_dismissed_${key}`
  27. )
  28. const isStillDismissed = Boolean(
  29. dismissedUntil && new Date(dismissedUntil) > new Date()
  30. )
  31. setStillDismissed(alertDismissed || isStillDismissed)
  32. }, [setStillDismissed, dismissedUntil, key, notificationLocation])
  33. const remindThemLater = useCallback(() => {
  34. const until = new Date()
  35. until.setDate(until.getDate() + 1) // 1 day
  36. setDismissedUntil(until)
  37. }, [setDismissedUntil])
  38. const saveDismissed = useCallback(() => {
  39. customLocalStorage.setItem(
  40. `${notificationLocation}.has_dismissed_${key}`,
  41. true
  42. )
  43. }, [key, notificationLocation])
  44. return { stillDissmissed, remindThemLater, saveDismissed }
  45. }