manifold/web/hooks/use-fold.ts

74 lines
1.8 KiB
TypeScript
Raw Permalink Normal View History

2022-01-23 06:51:19 +00:00
import { useEffect, useState } from 'react'
import { Fold } from '../../common/fold'
2022-01-26 20:03:32 +00:00
import { User } from '../../common/user'
import {
listenForFold,
listenForFolds,
2022-02-06 22:55:14 +00:00
listenForFoldsWithTags,
2022-01-26 20:03:32 +00:00
listenForFollow,
listenForFollowedFolds,
2022-01-26 20:03:32 +00:00
} from '../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>()
useEffect(() => {
if (tags && tags.length > 0) return listenForFoldsWithTags(tags, setFolds)
}, [tags])
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>()
useEffect(() => {
if (user) return listenForFollow(fold, user, setFollowing)
}, [fold, user])
return following
}
export const useFollowedFolds = (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
}