Skip to content

Commit fa26e67

Browse files
committed
add error on using duplicate reducer name
1 parent e236ed5 commit fa26e67

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/flexReducer.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ export function useFlexReducer(reducerName, reducer, initialState, options = { c
6060
if (!key.current) {
6161
key.current = genKey();
6262
reducerActiveComponent.set(reducerName, key.current);
63+
} else if (reducerActiveComponent.get(reducerName) !== key.current) {
64+
throw new Error(`Looks like you're trying to use more than one component with the same "${reducerName}" reducer.`);
6365
}
6466

6567
const [state, render] = useState(options.cache && cache[reducerName] || initialState);

test/flex-reducer.test.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,7 @@ describe('Flex Reducer', () => {
410410
expect(state.value).toBe('Hello Parent!')
411411
expect(cState.value).toBe('Bye Child!')
412412
})
413-
it('should not throw "reducer already in use" error if one component unmounted and another with the same reducer name is mounted and both happened through the same render', () => {
413+
it('should not throw duplicating error if one component unmounted and another with the same reducer name is mounted and both happened through the same render', () => {
414414
const Child2 = () => {
415415
useFlexReducer('child', cReducer, cInitialState)
416416
return <div />
@@ -433,6 +433,25 @@ describe('Flex Reducer', () => {
433433
)
434434
expect(result.error).not.toBe(undefined)
435435
})
436+
it('should throw an error if reducer name is duplicating on second render', () => {
437+
const Child2 = () => {
438+
useFlexReducer('child', cReducer, cInitialState)
439+
return <div />
440+
}
441+
Parent = () => {
442+
useFlexReducer('parent', pReducer, pInitialState)
443+
return (
444+
<div>
445+
<Child2 />
446+
<Child />
447+
</div>
448+
)
449+
}
450+
const { rerender } = rtl.render(<Parent />)
451+
expect(() => {
452+
rerender(<Parent />)
453+
}).toThrow('Looks like you\'re trying to use more than one component with the same "child" reducer.')
454+
})
436455
it('should throw an error if reducer is missing', () => {
437456
const { result } = renderHook(
438457
() => useFlexReducer('parent')

0 commit comments

Comments
 (0)