Skip to content

Commit

Permalink
fix(hooks): fix usePrevious does not work when passing state
Browse files Browse the repository at this point in the history
  • Loading branch information
u3u committed Aug 7, 2019
1 parent c009d5f commit 8567a04
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
14 changes: 7 additions & 7 deletions src/__tests__/usePrevious.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,22 @@ describe('usePrevious', () => {

it('should be previous state count', () => {
renderHook(async () => {
let count = state(0);
const prevCount = usePrevious(() => count);
const store = state({ count: 0 });
const prevCount = usePrevious(() => store.count);

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

count += 1;
store.count += 1;

await Vue.nextTick();
expect(count).toBe(1);
expect(store.count).toBe(1);
expect(prevCount.value).toBe(0);

count -= 1;
store.count -= 1;

await Vue.nextTick();
expect(count).toBe(0);
expect(store.count).toBe(0);
expect(prevCount.value).toBe(1);
});
});
Expand Down
6 changes: 3 additions & 3 deletions src/usePrevious.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { value, watch, Wrapper } from 'vue-function-api';

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

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

Expand Down

0 comments on commit 8567a04

Please sign in to comment.