Skip to content

Commit

Permalink
feat: useRefresh hook
Browse files Browse the repository at this point in the history
  • Loading branch information
warmachine028 committed Oct 24, 2024
1 parent 5dd249f commit e7b47f7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 28 deletions.
57 changes: 34 additions & 23 deletions client/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Post, PostPage } from '@/types'
import { useContext, useEffect } from 'react'
import { useContext, useEffect, useState } from 'react'
import { ThemeContext } from '@/contexts'
import { createPost, deletePost, getPosts, updatePost } from '@/api'
import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'
Expand Down Expand Up @@ -28,7 +28,7 @@ export const useGetPosts = () => {
}
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
initialPageParam: 1,
initialPageParam: 1
})

useEffect(() => {
Expand Down Expand Up @@ -82,14 +82,7 @@ export const useCreatePost = () => {
queryClient.setQueryData(['posts'], context?.previousData)
setOptimisticPages(previousPages)
},
onSuccess: () => {
// Force a fresh refetch from the server
queryClient.invalidateQueries({
queryKey: ['posts'],
exact: true,
refetchType: 'all'
})
}
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['posts'] })
})
}

Expand Down Expand Up @@ -122,12 +115,7 @@ export const useUpdatePost = () => {
queryClient.setQueryData(['posts'], context?.previousData)
setOptimisticPages(previousPages)
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['posts'],
refetchType: 'all'
})
}
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['posts'] })
})
}

Expand Down Expand Up @@ -155,11 +143,34 @@ export const useDeletePost = () => {

return { previousData }
},
onError: (_err, _postId, context) => {
queryClient.setQueryData(['posts'], context?.previousData)
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['posts'] })
}
onError: (_err, _postId, context) => queryClient.setQueryData(['posts'], context?.previousData),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['posts'] })
})
}
}

export const useRefresh = () => {
const queryClient = useQueryClient()
const { setOptimisticPages } = useStore()
const [refreshing, setRefreshing] = useState(false)

return {
refresh: async () => {
try {
setRefreshing(true)
// Reset the optimistic state first
setOptimisticPages([])

// Reset and refetch the posts query
await queryClient.resetQueries({ queryKey: ['posts'] })

return true
} catch (error) {
console.error('Failed to refresh:', error)
return false
} finally {
setRefreshing(false)
}
},
refreshing
}
}
17 changes: 12 additions & 5 deletions client/src/pages/Posts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Button, Input, Textarea, ScrollArea, Badge } from '@/components/ui'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Loader2, Plus, RefreshCcw } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import { useCreatePost, useGetPosts } from '@/hooks'
import { useCreatePost, useGetPosts, useRefresh } from '@/hooks'
import { Post } from '@/components'
import { useStore } from '@/store'

Expand Down Expand Up @@ -114,12 +114,13 @@ const CreatePost = () => {
const Posts = () => {
const { ref, inView } = useInView()
const { optimisticPages } = useStore()
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, status, refetch, isRefetching } = useGetPosts()
const { fetchNextPage, hasNextPage, isFetchingNextPage, status } = useGetPosts()
const {refresh, refreshing} = useRefresh()

if (inView && hasNextPage) {
fetchNextPage()
}
console.log(data)

return (
<div className="container mx-auto sm:p-4">
<CreatePost />
Expand All @@ -128,8 +129,14 @@ const Posts = () => {
<CardHeader className="bg-primary text-primary-foreground">
<div className="flex items-center justify-between">
<CardTitle className="text-2xl font-bold">Posts</CardTitle>
<Button variant="outline" onClick={() => refetch()} className="bg-primary">
<RefreshCcw className={`${isRefetching && 'animate-spin'}`} />
<Button
variant="outline"
onClick={refresh}
className="bg-primary"
disabled={refreshing}
>
<RefreshCcw className={`${refreshing && 'animate-spin'}`} />
{refreshing && <Loader2 className="h-4 w-4 animate-spin" />}
</Button>
</div>
<Badge variant="secondary" className="ml-2">
Expand Down

0 comments on commit e7b47f7

Please sign in to comment.