Adding redux to React app
1 min readSep 30, 2020
Will tell quick steps to add redux to your react app.
You can then create reducers and extend it as required by your project.
Install packages
npm install --save react-redux redux-thunk redux redux-devtools
npm install --save-dev redux-devtools-extension
In index.js ( where you document.getElementById(‘root’) )
import { Provider } from ‘react-redux’;
...ReactDOM.render(
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>,
document.getElementById('root'));
Creating Store
import { createStore,applyMiddleware,compose } from 'redux';
import Thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import Reducer from './reducers';const composeEnhancers = composeWithDevTools({
compose: window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose,
realtime: true,
trace: true,
traceLimit: 25,});const store = createStore(
Reducer,
composeEnhancers(applyMiddleware(Thunk)),);export default store;
Reducer and combining reducers
make reducers like
import axios from 'axios'
import { USERS } from '../../actions/constants';
const userReducer = (state = {}, { type, payload }) => {
switch (type) {
case USERS.SET_USER_DETAILS:{
axios.defaults.headers.post['autherization'] = payload
return { ...state,token:payload}
}
default:
return state;
}
};
export default userReducer;
now you will need to combine all the reducers
So in ./reducers/index.js
import { combineReducers } from 'redux';
import user from './user';
import voice from './voice'
const Reducer = combineReducers({
user,
voice
});
export default Reducer;
Using
in your component
import { connect } from 'react-redux';class App extends React.Component{
...
}const mapStateToProps = () => ({});
const mapDispatchToProps = dispatch => ({
saveToRedux: (data) => dispatch({
type:COURSE.SET_SELECTED_COURSE,
payload:data
})
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
That is it …