Skip to content

Instantly share code, notes, and snippets.

@rupeshtiwari
Last active September 1, 2017 17:05
Show Gist options
  • Save rupeshtiwari/0af8693d16f529d1cb3acba375fe75a9 to your computer and use it in GitHub Desktop.
Save rupeshtiwari/0af8693d16f529d1cb3acba375fe75a9 to your computer and use it in GitHub Desktop.
Redux Store with Reselect Selector example
// redux store reselect example same idea can be implemented with ngrx store/platform also.
// importing createStore
const {
createStore
} = Redux;
// importing of from rxjs
const {
of
} = Rx.Observable;
// importing reselect
const {
createSelector
} = Reselect;
// initial state
const initialState = {
name: 'Rupesh',
address: '',
age: ''
};
// utilities
const isNotEmptyString = (s) => s !== '';
const isValidNumber = (n) => n > 0;
// selectors
const getName = state => state.name;
const getAddress = state => state.address;
const getAge = state => state.age;
// reselctor
const isNameValid = createSelector(
getName, isNotEmptyString
);
const isAddressValid = createSelector(
getAddress, isNotEmptyString
);
const isAgeValid = createSelector(
getAge, isValidNumber
);
const isFormValid = createSelector(
isNameValid,
isAddressValid,
isAgeValid, (nameValid,
addressValid,
ageValid) =>
nameValid && addressValid && ageValid
);
// reducer
function reducer(state = initialState, action = {}) {
switch (action.type) {
case 'update':
{
return Object.assign({}, state, action.payload);
}
default:
return state;
}
}
// create store with given reducer
const store = createStore(reducer);
// dispatch action to update state
store.dispatch({
type: 'update',
payload: {
name: '',
address: '',
age: ''
}
});
// get next state
console.log('state after', store.getState());
// validate form
of(store.getState())
.map(isFormValid)
.subscribe(console.log.bind(this, 'Form Valid: '));
// dispatch action to update state
store.dispatch({
type: 'update',
payload: {
name: 'Anil',
address: 'Some Address',
age: 23
}
});
// get next state
console.log('state after', store.getState());
// validate form
of(store.getState())
.map(isFormValid)
.subscribe(console.log.bind(this, 'Form Valid: '));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment