Skip to content

Commit

Permalink
feat(hooks): add useTimeout hook
Browse files Browse the repository at this point in the history
  • Loading branch information
u3u committed Aug 7, 2019
1 parent c245487 commit 61db981
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/__tests__/useTimeout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { onMounted, onUnmounted } from 'vue-function-api';
import { useTimeout } from '..';
import renderHook from '../util/renderHook';

describe('useTimeout', () => {
it('should be defined', () => {
expect(useTimeout).toBeDefined();
});

it('should return true after 3000ms', () => {
const { vm } = renderHook<unknown>(() => {
jest.useFakeTimers();
const ready = useTimeout(3000);
expect(ready.value).toBe(false);

onMounted(() => {
expect(jest.getTimerCount()).toBe(1);
jest.runOnlyPendingTimers();
expect(ready.value).toBe(true);
});

onUnmounted(() => {
expect(jest.getTimerCount()).toBe(0);
});
});

vm.$destroy();
});
});
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export { default as useActions } from './useActions';
export { default as useRouter } from './useRouter';
export { default as useRef } from './useRef';
export { default as useMountedState } from './useMountedState';
export { default as useTimeout } from './useTimeout';

export default function install(Vue: VueConstructor) {
Vue.mixin({ beforeCreate: setRuntimeVM });
Expand Down
18 changes: 18 additions & 0 deletions src/useTimeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { value, onMounted, onUnmounted } from 'vue-function-api';

export default function useTimeout(delay = 0) {
const ready = value(false);
let timerId: number;

onMounted(() => {
timerId = window.setTimeout(() => {
ready.value = true;
}, delay);
});

onUnmounted(() => {
window.clearTimeout(timerId);
});

return ready;
}

0 comments on commit 61db981

Please sign in to comment.