Skip to content

Commit ba8f699

Browse files
committed
fix mutate wrong data + useApi loading state
1 parent a62b5df commit ba8f699

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

src/index.tsx

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ function createUseRevalidate<
115115
function createUseMutate<
116116
T,
117117
TData extends Record<keyof T, any>,
118+
TError extends Record<keyof T, any>,
118119
TVariables extends Record<keyof T, any>
119120
>(ctx: React.Context<ApiContext<T>>) {
120121
return function useMutate() {
@@ -124,11 +125,11 @@ function createUseMutate<
124125
K extends keyof T,
125126
TApiData extends TData[K],
126127
TApiVariables extends TVariables[K]
127-
>(key:K, variables: TApiVariables, callback: (prevData: TApiData) => TApiData) {
128+
>(key:K, variables: TApiVariables, callback: (prevData: TApiData | null | undefined) => TApiData | null | undefined) {
128129
const cacheKey = generateCacheKey(key, variables)
129-
const cacheData = cache.get(cacheKey) as TApiData
130-
const data = callback(cacheData)
131-
cache.set(cacheKey, data)
130+
const cacheData = cache.get(cacheKey) as ApiResult<TApiData, TError[K]>
131+
const data = callback(cacheData.data)
132+
cache.set(cacheKey, { ...cacheData, data })
132133
return data
133134
}, [cache])
134135

@@ -158,7 +159,7 @@ interface OnCompletedParams<
158159
X extends keyof T,
159160
TApiData extends TData[X],
160161
TApiVariables extends TVariables[X]
161-
>(key: X, variables: TApiVariables, callback: (prevData: TApiData) => TApiData) => TApiData
162+
>(key: X, variables: TApiVariables, callback: (prevData: TApiData | null | undefined) => TApiData | null | undefined) => TApiData | null | undefined
162163
}
163164

164165
export interface UseLazyApiOptions<
@@ -182,7 +183,7 @@ function createUseLazyApi<
182183
TVariables extends Record<keyof T, any>
183184
>(ctx: React.Context<ApiContext<T>>, apis: T) {
184185
const useRevalidate = createUseRevalidate<T, TData, TError, TVariables>(ctx, apis)
185-
const useMutate = createUseMutate<T, TData, TVariables>(ctx)
186+
const useMutate = createUseMutate<T, TData, TError, TVariables>(ctx)
186187

187188
return function useLazyApi<
188189
K extends keyof T,
@@ -371,7 +372,7 @@ function createUseApi<
371372

372373
return {
373374
...result,
374-
loading: loadingRef.current,
375+
loading: result.loading || loadingRef.current,
375376
called: calledRef.current
376377
}
377378
}

0 commit comments

Comments
 (0)