Some preface, see this post for how I implemented a barcode scanner. Long story short, when a barcode was scanned, it fired an event in jQuery, which allowed me in my components to do the following:
class EmployeeScreen extends Component {
componentDidMount() {
$(window).on('barcodeScan', (e) => {
if ( e.state.type !== 'E' ) {
alert('Please scan your employee badge');
} else {
this.setState({
badge: e.state.code
});
}
});
}
}
This was nice, because I was able to, on this specific component, check for employee badges and display errors otherwise. Now, I'm switching to a redux style, and I'm having trouble figuring out the best way to approach this. I figured the best way to start was to fire off a BARCODE_READ
action with redux-thunk:
dispatch({
type: BARCODE_READ,
event: {
type: this.barcodeRead.substr(0, 1),
code: this.barcodeRead.substr(1),
}
}));
The problem is, multiple reducers throughout my app need to listen for BARCODE_READ
, and do different actions. For example, let's say I have an following screens:
- Employee Screen: Using badge barcode, fetches employee information (First/Last name) and displays on page.
- Supervisor Screen: Using badge barcode, fetches employees who work under the user, and displays on the page.
Because this action is a part of my global app actions, I'm unsure how to apply it to individual screen actions. One way to do this, would be to dispatch actions from my employee reducer, but I've read this is an anti-pattern:
const reducer = (state = initialState, action) => {
switch (action.type) {
case BARCODE_READ:
if (action.event.type === 'E') {
dispatch({type: 'FETCH_EMPLOYEE_RECORD'});
}
return state;
case FETCH_EMPLOYEE_SUCCESS:
return {
...state,
employee: action.employee,
};
default: {
return state;
}
}
};
My supervisor reducer may dispatch FETCH_SUPERVSIOR_RECORD
, and views should process/update accordingly. Because this is an anti-pattern (And the fact I don't have access to dispatch from the reducer), what is the recommended approach?