Skip to content

Commit

Permalink
feat(hooks): add usePrevious hook
Browse files Browse the repository at this point in the history
  • Loading branch information
u3u committed Jul 18, 2019
1 parent 8483d43 commit f4d0dc8
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export default createComponent({
- [`useDate`](./src/useDate.ts) — Using [`dayjs`](https://github.com/iamkun/dayjs) to process date.
- [`useWindowSize`](./src/useWindowSize.ts) — Tracks `window` dimensions.
- [`useCounter`](./src/useCounter.ts) — Tracks state of a number.
- [`usePrevious`](./src/usePrevious.ts) — Returns the previous state or props.
- [`useRouter`](./src/useRouter.ts) — A hook for [`vue-router`](https://github.com/vuejs/vue-router).
- [`useStore`](./src/useStore.ts) — A hook for [`vuex`](https://github.com/vuejs/vuex).
- [`useState`](./src/useState.ts) — A hook for [`mapState`](https://vuex.vuejs.org/api/#mapstate).
Expand Down
34 changes: 34 additions & 0 deletions src/__tests__/usePrevious.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import Vue from 'vue';
import { value } from 'vue-function-api';
import usePrevious from '../usePrevious';
import renderHook from '../util/renderHook';

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

it('should be previous count', () => {
renderHook(() => {
const count = value(0);
const prevCount = usePrevious(count);

expect(count.value).toBe(0);
expect(prevCount.value).toBeUndefined();

count.value += 1;

Vue.nextTick().then(() => {
expect(count.value).toBe(1);
expect(prevCount.value).toBe(0);

count.value -= 1;

Vue.nextTick().then(() => {
expect(count.value).toBe(0);
expect(prevCount.value).toBe(1);
});
});
});
});
});
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export * from './useDate';
export { default as useDate } from './useDate';
export { default as useWindowSize } from './useWindowSize';
export { default as useCounter } from './useCounter';
export { default as usePrevious } from './usePrevious';
export { default as useStore } from './useStore';
export { default as useState } from './useState';
export { default as useGetters } from './useGetters';
Expand Down
11 changes: 11 additions & 0 deletions src/usePrevious.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { value, watch, Wrapper } from 'vue-function-api';

export default function usePrevious<T>(state: Wrapper<T> | T) {
const previous = value<T | undefined>(undefined);

watch('value' in state ? state : () => state, (_, oldVal) => {
previous.value = oldVal;
});

return previous;
}

0 comments on commit f4d0dc8

Please sign in to comment.