manifold/web/components/use-save-shares.ts
Boa 9ba7c04524
Sell shares mobile (#86)
* Abstract sell shares row to component

* Allow sell row to show just a button

This is nice for the feed and on a bet's mobile interface.

* Add and use floor shares

* Allow sell button on the same line as bet button

* Move use save shares to own file

* Make sure to sell non-integer shares

* Create SellButon & sell non-integer shares

* Remove props prefixes

* Break out sell modal and button
2022-04-20 08:13:39 -06:00

60 lines
1.5 KiB
TypeScript

import { Binary, CPMM, DPM, FullContract } from '../../common/contract'
import { Bet } from '../../common/bet'
import { useEffect, useState } from 'react'
import _ from 'lodash'
export const useSaveShares = (
contract: FullContract<CPMM | DPM, Binary>,
userBets: Bet[] | undefined
) => {
const [savedShares, setSavedShares] = useState<
| {
yesShares: number
noShares: number
yesFloorShares: number
noFloorShares: number
}
| undefined
>()
const [yesBets, noBets] = _.partition(
userBets ?? [],
(bet) => bet.outcome === 'YES'
)
const [yesShares, noShares] = [
_.sumBy(yesBets, (bet) => bet.shares),
_.sumBy(noBets, (bet) => bet.shares),
]
const [yesFloorShares, noFloorShares] = [
Math.floor(yesShares),
Math.floor(noShares),
]
useEffect(() => {
// Save yes and no shares to local storage.
const savedShares = localStorage.getItem(`${contract.id}-shares`)
if (!userBets && savedShares) {
setSavedShares(JSON.parse(savedShares))
}
if (userBets) {
const updatedShares = { yesShares, noShares }
localStorage.setItem(
`${contract.id}-shares`,
JSON.stringify(updatedShares)
)
}
}, [contract.id, userBets, noShares, yesShares])
if (userBets) return { yesShares, noShares, yesFloorShares, noFloorShares }
return (
savedShares ?? {
yesShares: 0,
noShares: 0,
yesFloorShares: 0,
noFloorShares: 0,
}
)
}