Set up REDUX-SAGA middleware for React App | Part 2 | Reduxsauce | Full codebase

Have you missed Part 1 of this post, here is the link


Ok now let's create Saga file for gettingPostList :

Saga/getPostListSaga.js

import { call,put } from 'redux-saga/effects'
import getPostListAction from '../Reducers/postListReducer'
import getPostListService from '../Services/getPostsService'

export default function* getPostList(action){
try{
const response = yield call(getPostListService);
yield put(getPostListAction.getPostListSuccess(response));
}catch(err){
yield put(getPostListAction.getPostListFailure());
}
}

After creating saga file we have to link saga with specific reducer in the RootSaga file

Saga/RootSaga.js

import { all,takeLatest } from 'redux-saga/effects'
import { GetPostListTypes } from '../Reducers/postListReducer'
import getPostList from './getPostListSaga'

export default function* rootSaga(){
yield all([
yield takeLatest(GetPostListTypes.GET_POST_LIST,getPostList)
]);
}

Well now our Saga and Reducer files are ready. Next we are going to create redux 'Store' and use Saga middleware on in

We also need to write the service file, where we will use axios , to make an API call, we are going create that file in Services/getPostsService.js

import axios from 'axios'
export default async function getPostListService(){
return await axios
.get(`http://dummy.restapiexample.com/api/v1/employees`,{
headers:{
"Content-Type":"application/json"
}
})
.then(response => {
return response;
})
.catch(function(error){
return error;
})
}

For that let's create store file in Store/store.js path, I am using logger here for better debugging option

import { createStore,applyMiddleware } from 'redux'
import { composeWithDevTools } from 'remote-redux-devtools'
import createSagaMiddleware from 'redux-saga'
import logger from 'redux-logger'

import rootReducer from '../Reducers/index'
import rootSaga from '../Saga/index'

const middleware = [];
const enhancers = [];

const sagaMiddleWare = createSagaMiddleware();
middleware.push(sagaMiddleWare);
middleware.push(logger);

const Async = ({dispatch}) => next => action => {
if(!action.payload || !action.payload.then){
return next(action)
}
action.payload.then(response => {
const newAction = {...action,payload:action};
dispatch(newAction);
})
}

middleware.push(Async);
enhancers.push(applyMiddleware(...middleware));

const store = createStore(rootReducer,composeWithDevTools(applyMiddleware(...middleware)));

sagaMiddleWare.run(rootSaga);

export default store;

Store file is created, now lets update App.js file passing the Store via Provider component. We will also add router to this file for page navigation purpose

import React from 'react';
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import Store from './Store/store'
import Routes from './Router'
const App = () =>{
return (
<Provider store={Store}>
<BrowserRouter>
<Routes />
</BrowserRouter>
</Provider>
);
}

export default App;

We have used 'Routes' component in App.js file, now we will created it

import React, {Component} from 'react'
import { Route,Switch } from 'react-router-dom'
import Home from './Components/Home/home'
class Routes extends Component{
render(){
return(
<Switch>
<Route path="/" exact component={Home} />
</Switch>
)
}
}

export default Routes;

Earlier we have created Home component earlier, now we are going to modify that file and add redux methods into it,

import React, { Component } from 'react'
import { connect } from 'react-redux'
import getPostListReducer from '../../Reducers/postListReducer'
class Home extends Component {
constructor(props){
super(props);
this.state = {
items:[]
}
}
componentDidMount(){
this.props.getPostListData()
}
componentWillReceiveProps(CreatedData){
console.log(CreatedData)
if(CreatedData && CreatedData.CreatedData && CreatedData.CreatedData.data &&
CreatedData.CreatedData.data.data){
this.setState({
items:CreatedData.CreatedData.data.data
})
}
}
render() {
console.log(this.state.items)
return (
<div>
Home
</div>
)
}
}
const mapStateToProps = state => {
console.log(state)
return{
CreatedData:state.getPostList.CreatedData
}
};
const mapDispatchToProps = dispatch => ({
getPostListData: data => {
dispatch(getPostListReducer.getPostList(data));
}
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Home);


Now we are all done, please notice when this component will be renderer for the first time, the state 'items' will be empty, but when redux gets data from the API it is going to re-render the component, and if API returns some set of value, will be stored in 'items' state.

Thank you for your time.

Comments

Popular posts from this blog

Best coding practice and structure for redux saga with react hooks | Separate watcher and worker saga | React clean code

How to use redux with React Hooks - Creating TodoList

Setting up Redux Devtools for React applications