yarn add redux react-redux- Create folder store
- create reducer.js
- createStore()
- setup store by adding Provider
- create mapDispatchToProps and
- mapStateToProps
import { connect } from 'react-redux';
const mapStateToProps = state => {
return {
ctr: state.ctrPr.counter,
storedResults: state.res.results
};
};
const mapDispatchToProps = dispatch => {
return {
onIncrementCounter: () => dispatch(actionCreators.increment()),
onAddCounter: () => dispatch(actionCreators.add(5)),
onDeleteResult: (idArg) => dispatch(actionCreators.deleteResult(idArg))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Counter);Then change the {this.state.something} to {this.props.ctr} - name props from mapStateToProps for state or mapDispatchToProps for actions
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';//Adding Middleware
const logger = store => {
return next => {
return action => {
console.log('[Middleware] Dispatching', action);
const result = next(action);
console.log('[Middleware] next state', store.getState());
return result;
}
}
}const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;const store = createStore(
rootReducer, composeEnhancers(applyMiddleware(logger)));
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
registerServiceWorker();What’s a thunk?!
A thunk is a function that wraps an expression to delay its evaluation.
// calculation of 1 + 2 is immediate
// x === 3
let x = 1 + 2;
// calculation of 1 + 2 is delayed
// foo can be called later to perform the calculation
// foo is a thunk!
let foo = () => 1 + 2;yarn add redux-thunk import thunk from 'redux-thunk';
const store = createStore(
rootReducer, composeEnhancers(applyMiddleware(logger, thunk)));