Skip to content

Instantly share code, notes, and snippets.

@p-jackson
Created January 20, 2020 09:55
Show Gist options
  • Save p-jackson/1ca023614930f4fcf89868ea216c2335 to your computer and use it in GitHub Desktop.
Save p-jackson/1ca023614930f4fcf89868ea216c2335 to your computer and use it in GitHub Desktop.
Using classes as action creators
// Action Creators
class IncrementCounter {
readonly type = 'INCREMENT_COUNTER';
}
class SetCounter {
readonly type = 'SET_COUNTER';
constructor( public newValue: number ) {}
}
type Action = IncrementCounter | SetCounter;
// Dispatch actions
dispatch( new IncrementCounter() );
dispatch( new SetCounter( 3 ) );
// Reduce actions
function reducer( state: number = 0, action: Action ) {
switch ( action.type ) {
case 'INCREMENT_COUNTER':
return state + 1;
case 'SET_COUNTER':
return action.newValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment