Skip to content

Commit

Permalink
add error on using duplicate reducer name
Browse files Browse the repository at this point in the history
  • Loading branch information
IpShot committed Jul 12, 2020
1 parent e236ed5 commit fa26e67
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/flexReducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
21 changes: 20 additions & 1 deletion test/flex-reducer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <div />
Expand All @@ -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 <div />
}
Parent = () => {
useFlexReducer('parent', pReducer, pInitialState)
return (
<div>
<Child2 />
<Child />
</div>
)
}
const { rerender } = rtl.render(<Parent />)
expect(() => {
rerender(<Parent />)
}).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')
Expand Down

0 comments on commit fa26e67

Please sign in to comment.