stacker.news/components/upvote.js

71 lines
2.1 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-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()
const [vote] = useMutation(
gql`
mutation vote($id: ID!, $sats: Int!) {
vote(id: $id, sats: $sats)
}`, {
update (cache, { data: { vote } }) {
cache.modify({
id: `Item:${itemId}`,
fields: {
2021-06-27 03:09:39 +00:00
meSats (existingMeSats = 0) {
return existingMeSats + vote
},
sats (existingSats = 0) {
2021-06-27 03:09:39 +00:00
return meSats === 0 ? existingSats + vote : existingSats
2021-04-27 21:30:58 +00:00
},
boost (existingBoost = 0) {
return meSats >= 1 ? existingBoost + vote : 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()
strike()
if (!itemId) return
2021-05-20 21:32:59 +00:00
try {
await vote({ variables: { id: itemId, sats: 1 } })
} 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>
)
}