stacker.news/components/upvote.js

89 lines
2.6 KiB
JavaScript
Raw Normal View History

2021-04-22 22:14:32 +00:00
import { LightningConsumer } from './lightning'
import UpArrow from '../svgs/lightning-arrow.svg'
import styles from './upvote.module.css'
import { gql, useMutation } from '@apollo/client'
import { signIn, useSession } from 'next-auth/client'
2021-05-20 21:32:59 +00:00
import { useFundError } from './fund-error'
2021-07-08 18:42:57 +00:00
import ActionTooltip from './action-tooltip'
2021-09-10 18:55:36 +00:00
import { useItemAct } from './item-act'
2021-04-27 21:30:58 +00:00
export default function UpVote ({ itemId, meSats, className }) {
const [session] = useSession()
2021-05-20 21:32:59 +00:00
const { setError } = useFundError()
2021-09-10 18:55:36 +00:00
const { setItem } = useItemAct()
2021-09-08 21:51:23 +00:00
const [act] = useMutation(
gql`
2021-09-10 18:55:36 +00:00
mutation act($id: ID!, $act: ItemAct! $sats: Int!) {
act(id: $id, act: $act, sats: $sats)
}`, {
2021-09-08 21:51:23 +00:00
update (cache, { data: { act } }) {
// read in the cached object so we don't use meSats prop
// which can be stale
const item = cache.readFragment({
id: `Item:${itemId}`,
fragment: gql`
2021-09-08 21:51:23 +00:00
fragment actedItem on Item {
meSats
}
`
})
cache.modify({
id: `Item:${itemId}`,
fields: {
2021-06-27 03:09:39 +00:00
meSats (existingMeSats = 0) {
2021-09-08 21:51:23 +00:00
return existingMeSats + act
2021-06-27 03:09:39 +00:00
},
sats (existingSats = 0) {
2021-09-08 21:51:23 +00:00
return item.meSats === 0 ? existingSats + act : existingSats
2021-04-27 21:30:58 +00:00
},
boost (existingBoost = 0) {
2021-09-08 21:51:23 +00:00
return item.meSats >= 1 ? existingBoost + act : existingBoost
}
}
})
}
}
)
2021-04-22 22:14:32 +00:00
return (
<LightningConsumer>
{({ strike }) =>
2021-08-13 21:12:19 +00:00
<ActionTooltip notForm>
2021-07-08 18:42:57 +00:00
<UpArrow
width={24}
height={24}
className={
`${styles.upvote}
${className || ''}
${meSats ? (meSats > 1 ? styles.stimi : styles.voted) : ''}`
}
2021-07-08 18:42:57 +00:00
onClick={
session
2021-06-24 23:56:01 +00:00
? async (e) => {
e.stopPropagation()
2021-09-10 18:55:36 +00:00
if (meSats >= 1) {
setItem({ itemId, act, strike })
return
}
2021-06-24 23:56:01 +00:00
strike()
if (!itemId) return
2021-09-10 18:55:36 +00:00
2021-05-20 21:32:59 +00:00
try {
2021-09-10 18:55:36 +00:00
await act({ variables: { id: itemId, act: 'VOTE', sats: 1 } })
2021-05-20 21:32:59 +00:00
} catch (error) {
if (error.toString().includes('insufficient funds')) {
setError(true)
return
}
throw new Error({ message: error.toString() })
}
}
: signIn
}
2021-07-08 18:42:57 +00:00
/>
</ActionTooltip>}
2021-04-22 22:14:32 +00:00
</LightningConsumer>
)
}