diff --git a/src/flexReducer.js b/src/flexReducer.js index 7dda6af..0422807 100644 --- a/src/flexReducer.js +++ b/src/flexReducer.js @@ -60,6 +60,8 @@ export function useFlexReducer(reducerName, reducer, initialState, options = { c if (!key.current) { key.current = genKey(); reducerActiveComponent.set(reducerName, key.current); + } else if (reducerActiveComponent.get(reducerName) !== key.current) { + throw new Error(`Looks like you're trying to use more than one component with the same "${reducerName}" reducer.`); } const [state, render] = useState(options.cache && cache[reducerName] || initialState); diff --git a/test/flex-reducer.test.js b/test/flex-reducer.test.js index 648e8d2..19d9a93 100644 --- a/test/flex-reducer.test.js +++ b/test/flex-reducer.test.js @@ -410,7 +410,7 @@ describe('Flex Reducer', () => { expect(state.value).toBe('Hello Parent!') expect(cState.value).toBe('Bye Child!') }) - 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', () => { + 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', () => { const Child2 = () => { useFlexReducer('child', cReducer, cInitialState) return
@@ -433,6 +433,25 @@ describe('Flex Reducer', () => { ) expect(result.error).not.toBe(undefined) }) + it('should throw an error if reducer name is duplicating on second render', () => { + const Child2 = () => { + useFlexReducer('child', cReducer, cInitialState) + return
+ } + Parent = () => { + useFlexReducer('parent', pReducer, pInitialState) + return ( +
+ + +
+ ) + } + const { rerender } = rtl.render() + expect(() => { + rerender() + }).toThrow('Looks like you\'re trying to use more than one component with the same "child" reducer.') + }) it('should throw an error if reducer is missing', () => { const { result } = renderHook( () => useFlexReducer('parent')