Skip to content

Instantly share code, notes, and snippets.

@jwrigh26
Last active May 3, 2019 23:08
Show Gist options
  • Save jwrigh26/402e5885adefb0e4ff97ae88dcd31ee5 to your computer and use it in GitHub Desktop.
Save jwrigh26/402e5885adefb0e4ff97ae88dcd31ee5 to your computer and use it in GitHub Desktop.
useReducer in a custom hook example
import {useReducer} from 'react';
export const rowAction = {
add: 'ACTION_ADD',
approve: 'ACTION_APPROVE',
edit: 'ACTION_EDIT',
note: 'ACTION_NOTE',
reset: 'ACTION_RESET',
};
export const defaultState = {
isAdding: false,
isApproving: false,
isEditing: false,
isNoteTaking: false,
};
export function reducer(state = defaultState, action = {}) {
if (action.type === rowAction.add) {
return {...defaultState, isAdding: true};
}
if (action.type === rowAction.approve) {
return {...defaultState, isApproving: true};
}
if (action.type === rowAction.edit) {
return {...defaultState, isEditing: true};
}
if (action.type === rowAction.note) {
return {...defaultState, isNoteTaking: true};
}
if (action.type === rowAction.reset) {
return defaultState;
}
return state;
}
export function useRowReducer() {
const [state, dispatch] = useReducer(reducer, defaultState);
return {state, dispatch};
}
export function useRowDispatch(dispatch, action) {
dispatch({type: action});
}
import React, {useEffect} from 'react';
import PropTypes from 'prop-types';
import {rowAction, useRowReducer, useRowDispatch} from './row.reducer';
import css from './row.scss?module';
function Foo({classNames}) {
const {state, dispatch} = useRowReducer();
const {isAdding, isApproving, isEditing, isNoteTaking} = state;
const dateValue = !isSecondaryLine ? date.Date.Value : undefined;
useEffect(() => {
// console.log('State ', date.Date.Value, isEditing);
}, [isEditing, isNoteTaking, isAdding, isApproving]);
function onHandleFoo() {
useRowDispatch(dispatch, rowAction.edit);
}
return (
<div className={[css.row, ...classNames].join(' ')} onClick={onHandleFoo}>
// Content goes here
</div>
);
}
Foo.defaultProps = {
classNames: [],
};
Foo.propTypes = {
classNames: PropTypes.arrayOf(PropTypes.string),
};
export default Foo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment