Skip to content

Instantly share code, notes, and snippets.

@chaffeqa
Created September 21, 2016 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaffeqa/99414862b9726c45c32e21a2296a67b0 to your computer and use it in GitHub Desktop.
Save chaffeqa/99414862b9726c45c32e21a2296a67b0 to your computer and use it in GitHub Desktop.
UI Redux Global Store
import { toggleElementAction, connect } from 'common';
function Dropdown({ uid, ui, dispatch }){
return (
<button type="button"
onClick={ dispatch(toggleElementAction('dropdown', uid)) }
className={ ui.dropdown == uid ? 'dropdown--toggled' : 'dropdown' }>
Toggle Dropdown: '{uid}'
</button>
)
}
Dropdown.propTypes = {
uid: Proptype.string.isRequired,
ui: Proptype.object.isRequired,
dispatch: Proptype.func.isRequired,
}
const DropdownWithUi = connect({ ui })(Dropdown)
export default DropdownWithUi
// Actions
export const TOGGLE_ELEMENT = 'UI_TOGGLE_ELEMENT';
export const ACQUIRE_HOLD = 'UI_ACQUIRE_HOLD';
export const RELEASE_HOLD = 'UI_RELEASE_HOLD';
// Action Creators
export function toggleElementAction(elementType, elementId) {
return (dispatch) => dispatch({ type: TOGGLE_ELEMENT, elementType, elementId });
}
export function acquireHoldAction(elementType) {
return (dispatch) => dispatch({ type: ACQUIRE_HOLD, elementType });
}
export function releaseHoldAction(elementType) {
return (dispatch) => dispatch({ type: RELEASE_HOLD, elementType });
}
// Reducer
const initialState = {};
export function uiReducer(state = initialState, action) {
switch (action.type) {
case TOGGLE_ELEMENT:
const newState = {}
newState[action.elementType] = state[action.elementType] == elementId ? undefined : elementId;
return Object.assign({}, state, newState);
case ACQUIRE_HOLD:
const newState = {}
newState[action.elementType] = parseInt(state[action.elementType] || 0) + 1;
return Object.assign({}, state, newState);
case ACQUIRE_HOLD:
const newState = {}
newState[action.elementType] = Math.max(parseInt(state[action.elementType] || 0) - 1, 0);
return Object.assign({}, state, newState);
default:
return state;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment