Skip to content

Commit

Permalink
Refactor actorHooks to include requestKey in useSharedCall
Browse files Browse the repository at this point in the history
  • Loading branch information
b3hr4d committed Oct 28, 2024
1 parent 8b21ec1 commit 9a66bd2
Showing 1 changed file with 20 additions and 13 deletions.
33 changes: 20 additions & 13 deletions packages/react/src/helpers/actorHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
UseMethodParameters,
UseMethodReturnType,
UseActorStore,
ActorMethodReturnType,
} from "../types"
import {
type VisitService,
Expand Down Expand Up @@ -139,26 +140,25 @@ export const actorHooks = <A = BaseActor>(
...options
}) => {
type M = typeof functionName

const requestKey = React.useMemo(() => generateRequestHash(args), [args])

const [sharedState, setSharedState] = useMethodState(
functionName,
requestKey
)

const reset = React.useCallback(
() => updateMethodState(functionName, requestKey, DEFAULT_STATE),
[functionName, requestKey]
)
const latestDataRef = React.useRef<ActorMethodReturnType<A[M]>>()

const reset = React.useCallback(() => {
updateMethodState(functionName, requestKey, DEFAULT_STATE)
latestDataRef.current = undefined
}, [functionName, requestKey])

const call = React.useCallback(
async (
eventOrReplaceArgs?: ActorMethodParameters<A[M]> | React.MouseEvent
) => {
setSharedState({ error: undefined, loading: true })
onLoading?.(true)

try {
const replaceArgs =
eventOrReplaceArgs instanceof Array ? eventOrReplaceArgs : args
Expand All @@ -167,32 +167,39 @@ export const actorHooks = <A = BaseActor>(
...(replaceArgs ?? args)
)

latestDataRef.current = data
setSharedState({ data, error: undefined, loading: false })

onSuccess?.(createCompiledResult(data))
onLoading?.(false)
return data
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Error calling method ${functionName}:`, error)
latestDataRef.current = undefined
setSharedState({
error: error as Error,
loading: false,
})
onError?.(error as Error)
onLoading?.(false)

if (throwOnError) throw error
}
},
[args, functionName, options, onError, onLoading, onSuccess, throwOnError]
)

const compileResult = React.useCallback(
() => createCompiledResult(sharedState?.data),
[sharedState?.data]
)
const compileResult = () => {
return createCompiledResult(latestDataRef.current || sharedState?.data)
}

return { call, reset, compileResult, requestKey, ...sharedState }
return {
call,
reset,
compileResult,
requestKey,
...sharedState,
}
}

const useQueryCall: UseQueryCall<A> = ({
Expand Down

0 comments on commit 9a66bd2

Please sign in to comment.