redux middleware saga

 import React, { Component } from 'react';

import { applyMiddleware,createStore } from 'redux';
//import { createLogger } from 'redux-logger';
import createSagaMiddleware from 'redux-saga';
import axios from 'axios';
export class RE5 extends Component {
  render() {
      
    const sagaMiddleware = createSagaMiddleware();

    //action:
    //action creators:
    const FETCH_USERS_REQUEST='FETCH_USERS_REQUEST'
    const FETCH_USERS_SUCCESS='FETCH_USERS_SUCCESS'
    const FETCH_USERS_FAILUER='FETCH_USERS_FAILURE'
    
    const fetchusersRequest =()=>{
      return {
           type:FETCH_USERS_REQUEST
            }
           }

const fetchUsersSuccess=users=>{
  return {
    type:FETCH_USERS_SUCCESS,
    payload:users   
  }
}

const fetchUsersFailure=(error)=>{
    return {
      type:FETCH_USERS_FAILUER,
      payload:error   
    }
  }
    const initialState={
                        loading:false,
                        users:[],
                        error:''
                       };
    
    const reducer=(state=initialState,action)=>{
      switch(action.type){
        case  FETCH_USERS_REQUEST:
          return{
                 ...state,
                 loading:true
                }
        case FETCH_USERS_SUCCESS:
          return{
                 ...state,
                loading:false,
                users:action.payload,
                error:''
                }
        case FETCH_USERS_FAILUER:
                    return{
                           ...state,
                          loading:false,
                          users:[],
                          error:action.payload
                          }
        defaultreturn state;
          }
        }
//action creator:
const fetchUsers=()=>{
        return function(dispatch){
            //loading true
            dispatch(fetchusersRequest())
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response=>{
    
    const users=response.data.map(user=>user.id)
   
dispatch(fetchUsersSuccess(users));
}).catch(error=>{
  
dispatch(fetchUsersFailure(error.message))
})
    }
}
   
   
  const store=createStore(reducer,
    applyMiddleware(sagaMiddleware)
        );




  //accepts reducer function and getstate
console.log("initialstate:",store.getState());

store.subscribe(()=>{
    console.log("store is now:",store.getState());
})

//store.dispatch(fetchUsers())
//store.dispatch(Decrement())
  
  return <div> 
    
<button onClick={()=>store.dispatch(fetchUsers())}>click1</button>
</div>;
  }
}

export default RE5;
 

Comments

Popular posts from this blog

interview questions js[ Anurag Singh ProCodrr]

reactnative_creation