2023-08-29 01:27:56 +00:00
|
|
|
import { useMutation } from '@apollo/client'
|
|
|
|
import { gql } from 'graphql-tag'
|
|
|
|
import Dropdown from 'react-bootstrap/Dropdown'
|
|
|
|
import { useToast } from './toast'
|
|
|
|
|
2023-09-18 18:20:02 +00:00
|
|
|
export default function SubscribeUserDropdownItem ({ user, target = 'posts' }) {
|
|
|
|
const isPosts = target === 'posts'
|
|
|
|
const mutation = isPosts ? 'subscribeUserPosts' : 'subscribeUserComments'
|
|
|
|
const userField = isPosts ? 'meSubscriptionPosts' : 'meSubscriptionComments'
|
2023-08-29 01:27:56 +00:00
|
|
|
const toaster = useToast()
|
2023-09-18 18:20:02 +00:00
|
|
|
const { id, [userField]: meSubscription } = user
|
2023-08-29 01:27:56 +00:00
|
|
|
const [subscribeUser] = useMutation(
|
|
|
|
gql`
|
2023-09-18 18:20:02 +00:00
|
|
|
mutation ${mutation}($id: ID!) {
|
|
|
|
${mutation}(id: $id) {
|
|
|
|
${userField}
|
2023-08-29 01:27:56 +00:00
|
|
|
}
|
|
|
|
}`, {
|
2023-09-18 18:20:02 +00:00
|
|
|
update (cache, { data: { [mutation]: subscribeUser } }) {
|
2023-08-29 01:27:56 +00:00
|
|
|
cache.modify({
|
|
|
|
id: `User:${id}`,
|
|
|
|
fields: {
|
2023-09-18 18:20:02 +00:00
|
|
|
[userField]: () => subscribeUser[userField]
|
2023-08-29 01:27:56 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
return (
|
|
|
|
<Dropdown.Item
|
|
|
|
onClick={async () => {
|
|
|
|
try {
|
|
|
|
await subscribeUser({ variables: { id } })
|
|
|
|
toaster.success(meSubscription ? 'unsubscribed' : 'subscribed')
|
|
|
|
} catch (err) {
|
|
|
|
console.error(err)
|
|
|
|
toaster.danger(meSubscription ? 'failed to unsubscribe' : 'failed to subscribe')
|
|
|
|
}
|
|
|
|
}}
|
|
|
|
>
|
2023-09-18 18:20:02 +00:00
|
|
|
{meSubscription
|
|
|
|
? `unsubscribe from ${isPosts ? 'posts' : 'comments'}`
|
|
|
|
: `subscribe to ${isPosts ? 'posts' : 'comments'}`}
|
2023-08-29 01:27:56 +00:00
|
|
|
</Dropdown.Item>
|
|
|
|
)
|
|
|
|
}
|