Skip to content

Commit

Permalink
fix(useAxios): prevent premature loading refs reset (#3076)
Browse files Browse the repository at this point in the history
  • Loading branch information
MickaelOth committed May 9, 2023
1 parent 7c54c36 commit b17010f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
17 changes: 17 additions & 0 deletions packages/integrations/useAxios/index.test.ts
Expand Up @@ -290,6 +290,23 @@ describe('useAxios', () => {
expect(error).toBeDefined()
})

it('should be loading on re-execute', async () => {
const onError = vi.fn()
const { isLoading, execute } = useAxios(url, config, { ...options, onError })

execute().catch(() => {})
await new Promise(resolve => setTimeout(resolve, 0))
expect(isLoading.value).toBeTruthy()

execute().catch(() => {})
await new Promise(resolve => setTimeout(resolve, 0))
expect(isLoading.value).toBeTruthy()

await execute().catch(() => {})
expect(isLoading.value).toBeFalsy()
expect(onError).toBeCalledTimes(2)
})

it('missing url', async () => {
// prevent stderr in jsdom xhr
console.error = vi.fn()
Expand Down
8 changes: 7 additions & 1 deletion packages/integrations/useAxios/index.ts
Expand Up @@ -204,6 +204,7 @@ export function useAxios<T = any, R = AxiosResponse<T>, D = any>(...args: any[])
catch: (...args) => waitUntilFinished().catch(...args),
} as Promise<OverallUseAxiosReturn<T, R, D>>

let executeCounter = 0
const execute: OverallUseAxiosReturn<T, R, D>['execute'] = (executeUrl: string | AxiosRequestConfig<D> | undefined = url, config: AxiosRequestConfig<D> = {}) => {
error.value = undefined
const _url = typeof executeUrl === 'string'
Expand All @@ -218,6 +219,10 @@ export function useAxios<T = any, R = AxiosResponse<T>, D = any>(...args: any[])
resetData()
abort()
loading(true)

executeCounter += 1
const currentExecuteCounter = executeCounter

instance(_url, { ...defaultConfig, ...typeof executeUrl === 'object' ? executeUrl : config, cancelToken: cancelToken.token })
.then((r: any) => {
response.value = r
Expand All @@ -231,7 +236,8 @@ export function useAxios<T = any, R = AxiosResponse<T>, D = any>(...args: any[])
})
.finally(() => {
options.onFinish?.()
loading(false)
if (currentExecuteCounter === executeCounter)
loading(false)
})
return promise
}
Expand Down

0 comments on commit b17010f

Please sign in to comment.