import { useState, useEffect } from 'react' import { useTranslation } from 'react-i18next' import { UserEmailData } from '../../../../../../types/user-email' import { Button } from 'react-bootstrap' import { isChangingAffiliation } from '../../utils/selectors' import { useUserEmailsContext } from '../../context/user-email-context' import DownshiftInput from './downshift-input' import Icon from '../../../../shared/components/icon' import useAsync from '../../../../shared/hooks/use-async' import { postJSON } from '../../../../infrastructure/fetch-json' import { defaults as roles } from '../../roles' import { defaults as departments } from '../../departments' type InstitutionAndRoleProps = { userEmailData: UserEmailData } function InstitutionAndRole({ userEmailData }: InstitutionAndRoleProps) { const { t } = useTranslation() const { isLoading, isError, runAsync } = useAsync() const { affiliation } = userEmailData const { state, setLoading: setUserEmailsContextLoading, setEmailAffiliationBeingEdited, updateAffiliation, } = useUserEmailsContext() const [role, setRole] = useState(affiliation?.role || '') const [department, setDepartment] = useState(affiliation?.department || '') useEffect(() => { setUserEmailsContextLoading(isLoading) }, [setUserEmailsContextLoading, isLoading]) const handleChangeAffiliation = () => { setEmailAffiliationBeingEdited(userEmailData.email) } const handleCancelAffiliationChange = () => { setEmailAffiliationBeingEdited(null) setRole(affiliation?.role || '') setDepartment(affiliation?.department || '') } const handleSubmit = (event: React.FormEvent) => { event.preventDefault() runAsync( postJSON('/user/emails/endorse', { body: { email: userEmailData.email, role, department, }, }) ) .then(() => { updateAffiliation(userEmailData.email, role, department) }) .catch(() => {}) } if (!affiliation?.institution) { return null } return ( <>
{affiliation.institution.name}
{!isChangingAffiliation(state, userEmailData.email) ? (
{(affiliation.role || affiliation.department) && ( <> {[affiliation.role, affiliation.department] .filter(Boolean) .join(', ')}
)}
) : (
{!isLoading && ( <> {t('save_or_cancel-or')} )}
)} {isError && ( {' '} {t('error_performing_request')} )} ) } export default InstitutionAndRole