use-user-contacts.ts 1.2 KB

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