overleaf/services/web/frontend/js/features/share-project-modal/hooks/use-user-contacts.js
Alf Eaton 42d06a091e Merge pull request #6064 from overleaf/jpa-fix-contacts-sorting
[web] share-project-modal: use server-side sorting of contacts

GitOrigin-RevId: fb66cf33a36b60c5014f87f001e682fa31ff7ff7
2021-12-13 09:03:52 +00:00

39 lines
1.1 KiB
JavaScript

import { useEffect, useState } from 'react'
import { getJSON } from '../../../infrastructure/fetch-json'
import useAbortController from '../../../shared/hooks/use-abort-controller'
export function useUserContacts() {
const [loading, setLoading] = useState(true)
const [data, setData] = useState(null)
const [error, setError] = useState(false)
const { signal } = useAbortController()
useEffect(() => {
getJSON('/user/contacts', { signal })
.then(data => {
setData(data.contacts.map(buildContact))
})
.catch(error => setError(error))
.finally(() => setLoading(false))
}, [signal])
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,
display: name ? `${name} <${contact.email}>` : contact.email,
}
}