11import { useStoredAccountContext } from "@/components/auth/account-context"
22import { useCollectionContext } from "@/components/collection/context"
3+ import { useHabitContext } from "@/components/habit/context"
34import { useOrderingContext } from "@/components/ordering/context"
45import { useRepoContentContext } from "@/components/repo/content-context"
56import { useRepoContext } from "@/components/repo/context"
@@ -21,7 +22,13 @@ import { toast } from "sonner"
2122import { decode , encode } from "uint8-to-base64"
2223
2324import { type StoredAccount , useStoredAccount } from "./auth"
24- import { type RepoContent , useStoredCollection , useStoredRepoContent , useStoredRepos } from "./git"
25+ import {
26+ type RepoContent ,
27+ useStoredCollection ,
28+ useStoredHabit ,
29+ useStoredRepoContent ,
30+ useStoredRepos ,
31+ } from "./git"
2532
2633export const client = new QueryClient ( )
2734
@@ -280,12 +287,15 @@ export const useUpdateHabit = (name: string) => {
280287}
281288
282289export const useBreakHabit = ( ) => {
290+ const { habit } = useHabitContext ( )
283291 const account = useStoredAccountContext ( )
284292 const repo = useRepoContext ( )
285293 const octokit = useOctokit ( )
286294
295+ const [ , setStored ] = useStoredHabit ( habit . name )
296+
287297 return useMutation ( {
288- mutationFn : ( habit : Habit ) => {
298+ mutationFn : ( ) => {
289299 if ( repo === undefined ) throw new Error ( "repo is not selected" )
290300
291301 return octokit . rest . repos . deleteFile ( {
@@ -296,8 +306,11 @@ export const useBreakHabit = () => {
296306 sha : habit . sha ,
297307 } )
298308 } ,
299- onSettled : async ( _ , __ , habit ) => {
309+ onSuccess : ( ) => {
310+ setStored ( undefined )
300311 client . removeQueries ( { queryKey : [ "repo" , repo . id , "habit" , habit . name ] } )
312+ } ,
313+ onSettled : async ( ) => {
301314 await client . invalidateQueries ( { queryKey : [ "repo" , repo . id , "content" ] } )
302315 } ,
303316 retry : handleError ( "Failed to break a habit" , { maxFailures : 0 } ) ,
@@ -318,6 +331,8 @@ export const useHabit = (name: string) => {
318331 const octokit = useOctokit ( )
319332 const { recordCompletion } = useOrderingContext ( )
320333
334+ const [ stored , setStored ] = useStoredHabit ( name )
335+
321336 return useQuery ( {
322337 queryKey : [ "repo" , repo . id , "habit" , name ] ,
323338 queryFn : async ( { signal } ) => {
@@ -336,8 +351,11 @@ export const useHabit = (name: string) => {
336351
337352 recordCompletion ( habit )
338353
354+ setStored ( { data : habit , updatedAt : new Date ( ) } )
339355 return habit
340356 } ,
357+ initialData : stored ?. data ,
358+ initialDataUpdatedAt : stored ?. updatedAt ?. getTime ?.( ) ,
341359 staleTime : 5 * 60 * 1000 , // todo
342360 retry : handleError ( `Failed to fetch habit data: ${ name } ` ) ,
343361 } )
0 commit comments