manifold/web/hooks/use-fold.ts

81 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-01-23 06:51:19 +00:00
import { useEffect, useState } from 'react'
import { Fold } from 'common/fold'
import { User } from 'common/user'
2022-01-26 20:03:32 +00:00
import {
listenForFold,
listenForFolds,
2022-02-06 22:55:14 +00:00
listenForFoldsWithTags,
2022-01-26 20:03:32 +00:00
listenForFollow,
listenForFollowedFolds,
} from 'web/lib/firebase/folds'
2022-01-23 06:51:19 +00:00
2022-01-27 06:38:22 +00:00
export const useFold = (foldId: string | undefined) => {
2022-01-23 06:51:19 +00:00
const [fold, setFold] = useState<Fold | null | undefined>()
useEffect(() => {
2022-01-27 06:38:22 +00:00
if (foldId) return listenForFold(foldId, setFold)
2022-01-23 06:51:19 +00:00
}, [foldId])
return fold
}
2022-01-24 05:47:20 +00:00
export const useFolds = () => {
const [folds, setFolds] = useState<Fold[] | undefined>()
useEffect(() => {
return listenForFolds(setFolds)
}, [])
return folds
}
2022-01-26 20:03:32 +00:00
2022-02-06 22:55:14 +00:00
export const useFoldsWithTags = (tags: string[] | undefined) => {
const [folds, setFolds] = useState<Fold[] | undefined>()
const tagsKey = tags?.join(',')
2022-02-06 22:55:14 +00:00
useEffect(() => {
if (tags && tags.length > 0) return listenForFoldsWithTags(tags, setFolds)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tagsKey])
2022-02-06 22:55:14 +00:00
return folds
}
2022-01-26 20:03:32 +00:00
export const useFollowingFold = (fold: Fold, user: User | null | undefined) => {
const [following, setFollowing] = useState<boolean | undefined>()
const foldId = fold?.id
const userId = user?.id
2022-01-26 20:03:32 +00:00
useEffect(() => {
if (userId) return listenForFollow(foldId, userId, setFollowing)
}, [foldId, userId])
2022-01-26 20:03:32 +00:00
return following
}
// Note: We cache followedFoldIds in localstorage to speed up the initial load
export const useFollowedFoldIds = (user: User | null | undefined) => {
const [followedFoldIds, setFollowedFoldIds] = useState<string[] | undefined>(
undefined
)
useEffect(() => {
if (user) {
const key = `followed-folds-${user.id}`
const followedFoldJson = localStorage.getItem(key)
if (followedFoldJson) {
setFollowedFoldIds(JSON.parse(followedFoldJson))
}
return listenForFollowedFolds(user.id, (foldIds) => {
setFollowedFoldIds(foldIds)
localStorage.setItem(key, JSON.stringify(foldIds))
})
}
}, [user])
return followedFoldIds
}