use-user-contacts.js 1.1 KB

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