Redux: It's Not Just for React
@borisonr
So what exactly is Redux...
"Predictable state container for JavaScript apps"
Evolution from Flux
Stores entire app's state in one place
Flux
created by Facebook in 2014
multiple stores and a dispatcher
more of a pattern than a framework
Redux
created by Dan Abramov in 2015
one store, multiple reducers
incredibly lightweight (2kB including dependencies)
vs.
So why do I need redux for my Angular app?
one-way data flow => happy app
more organized, less scattered
avoid side effects
Observable Pitstop
Angular (2+) and Redux love observables
Callbacks=>Promises=>Observables
Constant flow of data to subscribers
getMeSomeDataPlease().then(result =>{
console.log('woohoo we have data', result)
})
getMeSomeDataPlease().subscribe(result =>{
console.log('woohoo we have data', result)
})
promise
observable
Immutable Pitstop
redux values immutability=>super clear on outcomes
Libraries like Immutable.js will be your friend
Now let's actually use Redux...
Stores
Actions
Reducers
User
View
Model
npm install @ngrx/core @ngrx/store@2.2.3 --save
export interface IAppState extends Map<string,any> {
isEngaged: boolean;
}
function sheSaidYes(state, action) : IAppState {
return state.set('isEngaged', action)
}
export const ProposalReducer =
(state:Map<string,any> = Map<string,any>({}), {type, payload}) =>
{
switch (type) {
case 'SHE_SAID_YES':
return sheSaidYes(state, payload);
default:
return state;
}
};
import { StoreModule } from '@ngrx/store';
import { ProposalReducer } from './store';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule,
StoreModule.provideStore({ProposalReducer})
],
providers: []
bootstrap: [AppComponent]
})
export class AppModule { }
export class AppComponent {
public proposalStore: Observable<any>;
public didSheSayYes: boolean;
constructor(
private store: Store<IAppState>) { }
public ngOnInit(){
this.proposalStore = this.store.select('ProposalReducer');
this.proposalStore.subscribe(result => {
this.didSheSayYes = result.get('isEngaged');
})
}
public respond(response: boolean){
this.store.dispatch({
type: 'SHE_SAID_YES',
payload: response })
}
}
ngrx vs. angular-redux
ngrx is a Redux-inspired architecture that is heavily observables-based
angular-redux uses Redux itself as a dependency, and adds some Angular helpers (dependency-injection, observable wrappers)
Bonus perk!
timetravel debugging/
live code editing
easy testing
undo/redo
Further reading
What’s So Great About Redux? http://bit.ly/2w455M0
UI state management with Redux in Angular 4 http://bit.ly/2vcaEvL
Redux in Angular (2 and 4+) http://bit.ly/2tNTLqG
Comprehensive Introduction to @ngrx/store http://bit.ly/2lAP91W