Skip to content

Commit

Permalink
feat: 🎸 handle promise rice
Browse files Browse the repository at this point in the history
  • Loading branch information
ariesjia committed Jul 31, 2020
1 parent ecae3b4 commit 714358c
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 10 deletions.
36 changes: 34 additions & 2 deletions src/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,6 @@ describe("usePromiseCall test",() => {
await flushPromises();
})
})

it('should set loading when excute reload method', async () => {
const query = jest.fn().mockResolvedValue(null)
const { container } = render(() => {
Expand All @@ -197,9 +196,42 @@ describe("usePromiseCall test",() => {
act(() => {
container.hook.run('id')
})
expect(container.hook.loading).toBeTruthy();
await act(async () => {
await flushPromises();
})
expect(query).toHaveBeenCalledWith('id');
expect(container.hook.loading).toBeFalsy();
})
it('should handle promise race', async () => {
let called = false;
let count = 0;
const query = jest.fn().mockImplementation(() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(++count)
}, called ? 100 : 200)
})
})
const { container } = render(() => {
return usePromiseCall(
query,
[],
{ manual:true }
)
})
act(() => {
container.hook.run()
container.hook.run()
})
await act(async () => {
await flushTimeout(100);
})
expect(container.hook.data).toEqual(null);
expect(container.hook.loading).toBeTruthy();
await act(async () => {
await flushTimeout(100);
})
expect(container.hook.data).toEqual(2);
expect(container.hook.loading).toBeFalsy();
})
})
23 changes: 15 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const usePromiseCall = <T = any, K = any>(
) => {
const { interval = 100, initial = null, manual } = options
const didCancel = useRef(false);
const lastCall = useRef<number>(0);
const initialValue: State<T, K> = {
data: initial,
error: null,
Expand All @@ -47,6 +48,8 @@ const usePromiseCall = <T = any, K = any>(
);
const paramsRef = useRef();
const load = (requestParams: any) => {
lastCall.current += 1;
const callNumber = lastCall.current;
const params = getParamArray(requestParams);
dispatch({
error: null,
Expand All @@ -55,16 +58,20 @@ const usePromiseCall = <T = any, K = any>(
const promise = asyncMethod(...params);
promise.then(
res => {
dispatch({
data: res,
loading: false,
});
if(callNumber === lastCall.current) {
dispatch({
data: res,
loading: false,
});
}
},
err => {
dispatch({
error: err,
loading: false,
});
if(callNumber === lastCall.current) {
dispatch({
error: err,
loading: false,
});
}
},
);
return promise
Expand Down

0 comments on commit 714358c

Please sign in to comment.