From a0ed63070f2c5ec86e4c0936bc70314fed3d38f2 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Mon, 28 Mar 2022 11:56:04 -0500 Subject: [PATCH] Cache your shares in local storage so sell banner doesn't flicker. --- web/components/bet-panel.tsx | 55 ++++++++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 12 deletions(-) diff --git a/web/components/bet-panel.tsx b/web/components/bet-panel.tsx index 677d540c..9715a870 100644 --- a/web/components/bet-panel.tsx +++ b/web/components/bet-panel.tsx @@ -45,19 +45,13 @@ export function BetPanel(props: { const { mechanism } = contract const user = useUser() - const userBets = useUserContractBets(user?.id, contract.id) ?? [] + const userBets = useUserContractBets(user?.id, contract.id) const [tradeType, setTradeType] = useState<'BUY' | 'SELL'>('BUY') - const [yesBets, noBets] = _.partition( - userBets, - (bet) => bet.outcome === 'YES' - ) - const [yesShares, noShares] = [ - _.sumBy(yesBets, (bet) => bet.shares), - _.sumBy(noBets, (bet) => bet.shares), - ] + const { yesShares, noShares } = useSaveShares(contract, userBets) + const shares = yesShares || noShares const sharesOutcome = yesShares ? 'YES' : noShares ? 'NO' : undefined useEffect(() => { @@ -73,7 +67,7 @@ export function BetPanel(props: {
- You have {formatWithCommas(Math.floor(yesShares || noShares))}{' '} + You have {formatWithCommas(Math.floor(shares))}{' '} shares
@@ -115,7 +109,7 @@ export function BetPanel(props: { shares={yesShares || noShares} sharesOutcome={sharesOutcome} user={user} - userBets={userBets} + userBets={userBets ?? []} onSellSuccess={onBetSuccess} /> )} @@ -124,7 +118,7 @@ export function BetPanel(props: { @@ -417,3 +411,40 @@ function SellPanel(props: { ) } + +const useSaveShares = ( + contract: FullContract, + userBets: Bet[] | undefined +) => { + const [savedShares, setSavedShares] = useState< + { yesShares: number; noShares: number } | undefined + >() + + const [yesBets, noBets] = _.partition( + userBets ?? [], + (bet) => bet.outcome === 'YES' + ) + const [yesShares, noShares] = [ + _.sumBy(yesBets, (bet) => bet.shares), + _.sumBy(noBets, (bet) => bet.shares), + ] + + 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 } + return savedShares ?? { yesShares: 0, noShares: 0 } +}