use-user-contacts.js 1.1 KB

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