Skip to content

Commit

Permalink
fix: support fast-refresh (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
smmoosavi authored Nov 10, 2020
1 parent 0ddb999 commit 369d7dd
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ state; // => 2

### Rewiring

Please avoid changing the wire variable. if wire argument changed, an error will be thrown.
Please avoid changing the wire variable. if wire argument changed, a warning will be shown.

```tsx
// wrong, avoid.
Expand Down
8 changes: 5 additions & 3 deletions src/utils/use-stability-guard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { useStabilityGuard } from './use-stability-guard';

describe('useStabilityGuard', () => {
it('should throw error if wire changed', () => {
const { result, rerender } = renderHook(
const spy = jest.spyOn(global.console, 'warn');
spy.mockImplementation(() => {});
const { rerender } = renderHook(
({ firstWire }: { firstWire: boolean }) => {
const wire1 = useStateWire(null, 5);
const wire2 = useStateWire(null, 6);
Expand All @@ -15,7 +17,7 @@ describe('useStabilityGuard', () => {
);
rerender({ firstWire: false });

expect(result.error).toBeDefined();
expect(result.error.message).toBe('wire argument changed');
expect(spy).toBeCalledWith('Please avoid changing the wire variable.');
spy.mockRestore();
});
});
7 changes: 5 additions & 2 deletions src/utils/use-stability-guard.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { useState } from 'react';

let errorDisplayed = false;

export function useStabilityGuard(wire: unknown | null | undefined) {
const [preWire] = useState(wire);
if (preWire !== wire) {
throw new Error('wire argument changed');
if (preWire !== wire && !errorDisplayed) {
errorDisplayed = true;
console.warn('Please avoid changing the wire variable.');
}
}

0 comments on commit 369d7dd

Please sign in to comment.