install after react:
npm i redux react-redux redux-devtools-extension -S
Add the correct imports to index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from './reducers';
import App from './components/App';
import './index.css';
const store = createStore(rootReducer, composeWithDevTools())
ReactDOM.render(
<Provider
store= {store}>
<App />
</Provider>,
document.getElementById('root')
);
need:
{ connect } from 'react-redux'
to connect components (that need access to store) to the store
export default connect(mapStateToProps, mapDispatchToProps)(componentName)
you will need to write mapStateToProps and mapDispatchToProps
const mapStateToProps = (state) => ({
//needs to return an object
//the properties in the object become available in props
})
const mapDispatchToProps = dispatch => ({
//makes updates to global state
//returns an object
//define a methods that dispatch an action
methodName : ( arg ) => dispatch( methodFromStore(arg) ),
})
can also use (prop name same as action name)
const mapDispatchToProps = dispatch => (
bindActionCreators({
methodFromStore1,
methodFromStore2,
...,
methodFromStoreN
}
, dispatch)
)
Use with:
import { bindActionCreators } from 'redux';
import your actions
import { xxx, yyy } from '../actions'
Reducer index.js set-up
import { combineReducers } from 'redux';
import { todos } from './todos' //import all of your reducers
const rootReducer = combineReducers ({
todos
})
export default rootReducer;
Reducer Set-up
export const todos = ( state = [] , action) => {
switch(action.type){
case 'DELETE_TODO':
console.log('not yet');
break;
case 'ADD_TODO':
return [...state, { id: Date.now(), todo: action.todo, completed: false }]
default: //need the default just when there is not a matching case.
return state;
}
}