2021-03-12 05:23:46 -05:00
|
|
|
import { useEffect, useState } from 'react'
|
|
|
|
import { getJSON } from '../../../infrastructure/fetch-json'
|
2021-06-23 04:09:23 -04:00
|
|
|
import useAbortController from '../../../shared/hooks/use-abort-controller'
|
2021-03-12 05:23:46 -05:00
|
|
|
|
|
|
|
const contactCollator = new Intl.Collator('en')
|
|
|
|
|
|
|
|
const alphabetical = (a, b) =>
|
|
|
|
contactCollator.compare(a.name, b.name) ||
|
|
|
|
contactCollator.compare(a.email, b.email)
|
|
|
|
|
|
|
|
export function useUserContacts() {
|
|
|
|
const [loading, setLoading] = useState(true)
|
|
|
|
const [data, setData] = useState(null)
|
|
|
|
const [error, setError] = useState(false)
|
|
|
|
|
2021-06-23 04:09:23 -04:00
|
|
|
const { signal } = useAbortController()
|
|
|
|
|
2021-03-12 05:23:46 -05:00
|
|
|
useEffect(() => {
|
2021-06-23 04:09:23 -04:00
|
|
|
getJSON('/user/contacts', { signal })
|
2021-03-12 05:23:46 -05:00
|
|
|
.then(data => {
|
|
|
|
setData(data.contacts.map(buildContact).sort(alphabetical))
|
|
|
|
})
|
|
|
|
.catch(error => setError(error))
|
|
|
|
.finally(() => setLoading(false))
|
2021-06-23 04:09:23 -04:00
|
|
|
}, [signal])
|
2021-03-12 05:23:46 -05:00
|
|
|
|
|
|
|
return { loading, data, error }
|
|
|
|
}
|
|
|
|
|
|
|
|
function buildContact(contact) {
|
|
|
|
const [emailPrefix] = contact.email.split('@')
|
|
|
|
|
|
|
|
// the name is not just the default "email prefix as first name"
|
|
|
|
const hasName = contact.last_name || contact.first_name !== emailPrefix
|
|
|
|
|
|
|
|
const name = hasName
|
|
|
|
? [contact.first_name, contact.last_name].filter(Boolean).join(' ')
|
|
|
|
: ''
|
|
|
|
|
|
|
|
return {
|
|
|
|
...contact,
|
|
|
|
name,
|
2021-04-27 03:52:58 -04:00
|
|
|
display: name ? `${name} <${contact.email}>` : contact.email,
|
2021-03-12 05:23:46 -05:00
|
|
|
}
|
|
|
|
}
|