Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
useInviteContacts
import React from 'react'
import { Contact } from 'react-native-contacts'
import { difference, without } from 'rambda'
type RoleStateKey = 'administrator' | 'guest' | 'contributor'
export type UseInviteContacts = {
toggleRecipient: (c: Contact) => void
toggleAdministrator: (c: Contact) => void
toggleContributor: (c: Contact) => void
roles: { [key in RoleStateKey]: string[] }
recipients: string[]
}
export function useInviteContacts(): UseInviteContacts {
const [recipients, setRecipients] = React.useState<string[]>([])
const initialArray: string[] = []
const [roles, setRoles] = React.useState<
{ [key in RoleStateKey]: string[] }
>({
administrator: initialArray,
contributor: initialArray,
guest: initialArray
})
const toggleContributor = React.useCallback((c: Contact) => {
return setRoles(state => {
if (state.contributor.find(r => r === c.recordID)) {
return {
...state,
contributor: without([c.recordID])(state.contributor),
guest: [...state.guest, c.recordID]
}
} else {
const filtered = {
guest: without([c.recordID])(state.guest),
administrator: without([c.recordID])(state.administrator),
contributor: without([c.recordID])(state.contributor)
}
return {
...filtered,
contributor: [...state.contributor, c.recordID],
guest: difference(recipients, [
...state.contributor,
...state.administrator
])
}
}
})
}, [recipients])
const toggleAdministrator = React.useCallback(
(c: Contact) => {
return setRoles((state) => {
if (state.administrator.find((r) => r === c.recordID)) {
return {
...state,
administrator: without([c.recordID])(state.contributor),
contributor: [...state.contributor, c.recordID]
}
} else {
const filtered = {
guest: without([c.recordID])(state.guest),
administrator: without([c.recordID])(state.administrator),
contributor: without([c.recordID])(state.contributor)
}
return {
...filtered,
administrator: [...state.administrator, c.recordID],
guest: difference(recipients, [
...state.contributor,
...state.administrator
])
}
}
})
},
[recipients]
)
const toggleRecipient = React.useCallback((contact: Contact) => {
toggleContributor(contact)
return setRecipients(state => {
if (state.find(x => x === contact.recordID)) {
return state.filter(r => r !== contact.recordID)
}
return [...state, contact.recordID]
})
}, [toggleContributor])
return {
recipients,
roles,
toggleRecipient,
toggleAdministrator,
toggleContributor
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment