1- import { createContext , useCallback , useContext , useEffect , useReducer , useRef } from 'react'
1+ import { createContext , useCallback , useContext , useEffect , useMemo , useReducer , useRef } from 'react'
22
33const isObj = ( obj : unknown ) : obj is object => (
44 typeof obj === 'object' &&
@@ -24,6 +24,17 @@ function useValueRef<T>(value: T) {
2424 return ref
2525}
2626
27+ function useMemoValue < T > ( value : T ) {
28+ const ref = useRef ( value )
29+
30+ return useMemo ( ( ) => {
31+ if ( JSON . stringify ( value ) !== JSON . stringify ( ref . current ) ) {
32+ ref . current = value
33+ }
34+ return ref . current
35+ } , [ value ] )
36+ }
37+
2738export type ApiVariables < T extends Partial < Record < 'body' | 'query' | 'body' , any > > = { } > = T
2839
2940interface ApiConfig < APIs > {
@@ -136,8 +147,9 @@ function createUseApi<
136147 TApiVariables extends TVariables [ K ]
137148 > ( key : K , opts : UseLazyApiOptions < TApiVariables > = { } ) {
138149 const [ fetch , result ] = useLazyApi < K , TApiData , TApiError , TApiVariables > ( key , opts )
150+ const latestVariables = useMemoValue ( opts . variables )
139151
140- useEffect ( ( ) => { fetch ( ) } , [ fetch ] )
152+ useEffect ( ( ) => { fetch ( ) } , [ fetch , latestVariables ] )
141153
142154 return result
143155 }
0 commit comments