use-user-contacts.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { useEffect, useState } from 'react'
  2. import { getJSON } from '../../../infrastructure/fetch-json'
  3. import useAbortController from '../../../shared/hooks/use-abort-controller'
  4. const contactCollator = new Intl.Collator('en')
  5. const alphabetical = (a, b) =>
  6. contactCollator.compare(a.name, b.name) ||
  7. contactCollator.compare(a.email, b.email)
  8. export function useUserContacts() {
  9. const [loading, setLoading] = useState(true)
  10. const [data, setData] = useState(null)
  11. const [error, setError] = useState(false)
  12. const { signal } = useAbortController()
  13. useEffect(() => {
  14. getJSON('/user/contacts', { signal })
  15. .then(data => {
  16. setData(data.contacts.map(buildContact).sort(alphabetical))
  17. })
  18. .catch(error => setError(error))
  19. .finally(() => setLoading(false))
  20. }, [signal])
  21. return { loading, data, error }
  22. }
  23. function buildContact(contact) {
  24. const [emailPrefix] = contact.email.split('@')
  25. // the name is not just the default "email prefix as first name"
  26. const hasName = contact.last_name || contact.first_name !== emailPrefix
  27. const name = hasName
  28. ? [contact.first_name, contact.last_name].filter(Boolean).join(' ')
  29. : ''
  30. return {
  31. ...contact,
  32. name,
  33. display: name ? `${name} <${contact.email}>` : contact.email,
  34. }
  35. }