tooot/src/components/Relationship/Outgoing.tsx

128 lines
3.4 KiB
TypeScript
Raw Normal View History

import Button from '@components/Button'
import haptics from '@components/haptics'
import { toast } from '@components/toast'
2021-01-11 21:36:57 +01:00
import {
QueryKeyRelationship,
useRelationshipMutation,
useRelationshipQuery
2021-01-10 02:12:14 +01:00
} from '@utils/queryHooks/relationship'
2021-01-11 21:36:57 +01:00
import React from 'react'
import { useTranslation } from 'react-i18next'
2021-01-11 21:36:57 +01:00
import { useQueryClient } from 'react-query'
export interface Props {
id: Mastodon.Account['id']
}
2021-01-11 21:36:57 +01:00
const RelationshipOutgoing = React.memo(
({ id }: Props) => {
const { t } = useTranslation()
2021-01-11 21:36:57 +01:00
const query = useRelationshipQuery({ id })
2021-01-11 21:36:57 +01:00
const queryKeyRelationship: QueryKeyRelationship = ['Relationship', { id }]
const queryClient = useQueryClient()
const mutation = useRelationshipMutation({
onSuccess: res => {
haptics('Success')
queryClient.setQueryData<Mastodon.Relationship[]>(
queryKeyRelationship,
[res]
)
},
onError: (err: any, { type }) => {
haptics('Error')
toast({
type: 'error',
message: t('common:toastMessage.error.message', {
function: t(`relationship:${type}.function`)
}),
...(err.status &&
typeof err.status === 'number' &&
err.data &&
err.data.error &&
typeof err.data.error === 'string' && {
description: err.data.error
})
})
}
})
2021-01-11 21:36:57 +01:00
let content: string
let onPress: () => void
2021-01-11 21:36:57 +01:00
if (query.isError) {
content = t('relationship:button.error')
onPress = () => {}
} else {
2021-01-11 21:36:57 +01:00
if (query.data?.blocked_by) {
content = t('relationship:button.blocked_by')
onPress = () => null
} else {
2021-01-11 21:36:57 +01:00
if (query.data?.blocking) {
content = t('relationship:button.blocking')
onPress = () =>
mutation.mutate({
2021-01-11 21:36:57 +01:00
id,
type: 'outgoing',
payload: {
action: 'block',
state: query.data?.blocking
}
})
} else {
2021-01-11 21:36:57 +01:00
if (query.data?.following) {
content = t('relationship:button.following')
onPress = () =>
mutation.mutate({
2021-01-11 21:36:57 +01:00
id,
type: 'outgoing',
payload: {
action: 'follow',
state: query.data?.following
}
})
} else {
2021-01-11 21:36:57 +01:00
if (query.data?.requested) {
content = t('relationship:button.requested')
onPress = () =>
mutation.mutate({
id,
type: 'outgoing',
payload: {
action: 'follow',
state: query.data?.requested
}
})
} else {
content = t('relationship:button.default')
onPress = () =>
mutation.mutate({
id,
type: 'outgoing',
payload: {
action: 'follow',
state: false
}
})
}
}
}
}
}
2021-01-11 21:36:57 +01:00
return (
<Button
type='text'
content={content}
onPress={onPress}
loading={query.isLoading || mutation.isLoading}
disabled={query.isError || query.data?.blocked_by}
/>
)
},
() => true
)
export default RelationshipOutgoing