57 lines
1.3 KiB
TypeScript
57 lines
1.3 KiB
TypeScript
import { useState } from 'react'
|
|
|
|
export function useOptimisticUpdate<T>(initialData: T) {
|
|
const [data, setData] = useState<T>(initialData)
|
|
const [isOptimistic, setIsOptimistic] = useState(false)
|
|
|
|
const updateOptimistically = async (
|
|
optimisticValue: T,
|
|
asyncUpdate: () => Promise<T>
|
|
) => {
|
|
setData(optimisticValue)
|
|
setIsOptimistic(true)
|
|
|
|
try {
|
|
const result = await asyncUpdate()
|
|
setData(result)
|
|
setIsOptimistic(false)
|
|
return result
|
|
} catch (error) {
|
|
setData(initialData)
|
|
setIsOptimistic(false)
|
|
throw error
|
|
}
|
|
}
|
|
|
|
return { data, isOptimistic, updateOptimistically, setData }
|
|
}
|
|
|
|
export function useOptimisticLike(initialLiked: boolean, initialCount: number) {
|
|
const [liked, setLiked] = useState(initialLiked)
|
|
const [count, setCount] = useState(initialCount)
|
|
const [loading, setLoading] = useState(false)
|
|
|
|
const toggleLike = async (apiCall: () => Promise<void>) => {
|
|
if (loading) return
|
|
|
|
const prevLiked = liked
|
|
const prevCount = count
|
|
|
|
setLiked(!liked)
|
|
setCount(liked ? count - 1 : count + 1)
|
|
setLoading(true)
|
|
|
|
try {
|
|
await apiCall()
|
|
setLoading(false)
|
|
} catch (error) {
|
|
setLiked(prevLiked)
|
|
setCount(prevCount)
|
|
setLoading(false)
|
|
throw error
|
|
}
|
|
}
|
|
|
|
return { liked, count, loading, toggleLike }
|
|
}
|