diff --git a/package.json b/package.json index 1f972739..e7ac717f 100644 --- a/package.json +++ b/package.json @@ -62,7 +62,8 @@ "@commitlint/config-conventional": "8.3.4", "@types/jest": "25.1.3", "@types/react": "16.9.23", - "@types/react-native": "0.61.17", "commitizen": "4.0.3", + "@types/react-native": "0.61.17", + "commitizen": "4.0.3", "cz-conventional-changelog": "3.1.0", "husky": "4.2.3", "lint-staged": "10.0.8", diff --git a/src/hooks/useBarcodeFinder.ts b/src/hooks/useBarcodeFinder.ts index 4801c04e..8878ca4c 100644 --- a/src/hooks/useBarcodeFinder.ts +++ b/src/hooks/useBarcodeFinder.ts @@ -1,6 +1,6 @@ -import { CustomBarcodeRead } from 'interfaces'; -import { useCallback, useState } from 'react'; +import { Reducer, useCallback, useReducer, useState } from 'react'; import { LayoutChangeEvent } from 'react-native'; +import { BoundingRect, CustomBarcodeRead } from '../interfaces'; /** * @internal @@ -14,10 +14,32 @@ export default ( customBarcodeRead?: CustomBarcodeRead | number ) => { const [barcodeRead, setBarcodeRead] = useState(false); - const [finderWidth, setFinderWidth] = useState(0); - const [finderHeight, setFinderHeight] = useState(0); - const [finderX, setFinderX] = useState(0); - const [finderY, setFinderY] = useState(0); + const [state, dispatch] = useReducer< + Reducer< + BoundingRect, + { + type: 'SET'; + payload: BoundingRect; + } + > + >( + (prev, action) => { + switch (action.type) { + case 'SET': { + return { ...prev, ...action.payload }; + } + default: { + return prev; + } + } + }, + { + width: 0, + height: 0, + x: 0, + y: 0, + } + ); const _onBarcodeFinderLayoutChange = useCallback( (event: LayoutChangeEvent) => { const { @@ -25,12 +47,9 @@ export default ( layout: { height, width, x, y }, }, } = event; - setFinderWidth(width); - setFinderHeight(height); - setFinderX(x); - setFinderY(y); + dispatch({ type: 'SET', payload: { height, width, x, y } }); }, - [finderX, finderY, finderHeight, finderWidth] + [state.height, state.width, state.x, state.y] ); let timeoutId = 0; @@ -61,10 +80,10 @@ export default ( customBarcodeRead && typeof customBarcodeRead === 'object' ? null : barcodeRead, - finderX, - finderY, - finderWidth, - finderHeight, + finderX: state.x, + finderY: state.y, + finderWidth: state.width, + finderHeight: state.height, onBarcodeFinderLayoutChange: _onBarcodeFinderLayoutChange, processingReadBarcode, };