Part 1
"Redux is a predictable state container for JavaScript apps.
It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger."
from reactjs/redux repo
Store will store your application state.
The Store is king of the "database" of client side. it's the 'single source of truth' and can be queried from any place of the application.
snapshot of store at any point will supply a complete representation of relevant application state.
Pure functions that takes 2 params:
Reducer function will return a new state object
// Action interface
export interface Action {
type: string;
payload?: any;
}
import { Action } from '@ngrx/store';
export const GET_EVENTS = 'GET_EVENTS';
export const GET_EVENTS_SUCCESS = 'GET_EVENTS_SUCCESS';
export const ADD_EVENTS = 'ADD_EVENTS';
const initialState: EventsState = {
events: [],
loading: false,
...
};
export interface EventsState {
events: any;
loading: boolean;
...
}
export const eventsReducer = (state = initialState, action: Action): EventsState => {
switch (action.type) {
case GET_EVENTS:
return Object.assign({}, state, {
loading: true
});
case GET_EVENTS_SUCCESS:
return Object.assign({}, state, {
loading: false
});
case ADD_EVENTS:
return Object.assign({}, state, {
events: state.events.concat(action.payload)
});
....
default:
return state;
}
}
bootstrap(AppComponent, [
...
provideStore({ events: eventsReducer }),
instrumentStore(),
...
]);
import { provideStore } from '@ngrx/store';
import { instrumentStore } from '@ngrx/store-devtools';
import { Store } from '@ngrx/store';
import { GET_EVENTS, GET_EVENTS_SUCCESS, ADD_EVENTS } from '../reducers/events.reducer';
constructor(public store: Store<any>, ...)
getEvents(start: number, end: number) {
this.store.dispatch({ type: GET_EVENTS });
this.eventsService.getEvents(start, end)
.subscribe(res => {
this.store.dispatch({ type: GET_EVENTS_SUCCESS });
this.store.dispatch({ type: ADD_EVENTS, payload: res.data.map(event => new EventModel(event)) });
});
}
constructor(public store: Store<any>, ...) {
store.select(s => s.events).subscribe(eventsState => {
this.events = eventsState.events;
this.loading = eventsState.loading;
...
});
}
Open installed chrome extension 'Redux Devtools' and see the actions goes in.
Need help?
https://gitter.im/dvh91/kmeetups