manifold/web/hooks/use-seen-contracts.ts
Marshall Polaris 03858e4a8c
Make a React context to be the source of truth for authenticated user (#675)
* Make a React context to manage the logged in user events

* Remove unnecessary new user creation promise machinery

* Slight refactoring to auth context code

* Improvements in response to James feedback
2022-07-21 00:38:26 -07:00

48 lines
1.1 KiB
TypeScript

import { mapValues } from 'lodash'
import { useEffect, useState } from 'react'
import { Contract } from 'common/contract'
import { trackView } from 'web/lib/firebase/tracking'
import { useIsVisible } from './use-is-visible'
import { useUser } from './use-user'
export const useSeenContracts = () => {
const [seenContracts, setSeenContracts] = useState<{
[contractId: string]: number
}>({})
useEffect(() => {
setSeenContracts(getSeenContracts())
}, [])
return seenContracts
}
export const useSaveSeenContract = (
elem: HTMLElement | null,
contract: Contract
) => {
const isVisible = useIsVisible(elem)
const user = useUser()
useEffect(() => {
if (isVisible && user) {
const newSeenContracts = {
...getSeenContracts(),
[contract.id]: Date.now(),
}
localStorage.setItem(key, JSON.stringify(newSeenContracts))
trackView(user.id, contract.id)
}
}, [isVisible, user, contract])
}
const key = 'feed-seen-contracts'
const getSeenContracts = () => {
return mapValues(
JSON.parse(localStorage.getItem(key) ?? '{}'),
(time) => +time
)
}