Redux middleware
Middleware:
its way to extend redux with
custom functionality
extra feature with redux
provides a 3rd party extension
point b/w dispatching an action
and the moment it reaches the
reducer
middleware use:
logging,crash reporting
performing asysnchronous task
etc
Asnc action creators:
axios:requests to an api end poing
redux thunk
define async action creators
midleware
import React, { Component } from 'react';
import { applyMiddleware,createStore } from 'redux';
//import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import axios from 'axios';
export class RE4 extends Component {
render() {
//const logger = createLogger();
//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
}
default: return state;
}
}
//action creator:
const fetchUsers=()=>{
//can return functions by using thunk
//instead of an action the function can do async task
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(thunk)
);
//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 RE4;
h
Comments
Post a Comment