I’m trying to get the updated state as {loading:true, users:[], error:”} after FETCH_USERS_REQUEST action but I’m getting same as an initial state , Can anyone tell me what is the issue?
const redux = require('redux');
const reduxLogger = require('redux-logger');
const createStore = redux.createStore;
const applyMiddleWare = redux.applyMiddleware
const thunkMiddleWare = require('redux-thunk').thunk
const axios = require('axios');
const logger = reduxLogger.createLogger()
const initialState={
loading: false,
users:[],
error:''
}
const FETCH_USERS_REQUEST='FETCH_USERS_REQUEST';
const FETCH_USERS_SUCCESS='FETCH_USERS_SUCCESS';
const FETCH_USERS_FAILURE='FETCH_USERS_FAILURE'
const fetchUsersRequest = () => {
console.log("asdfghjk")
return {
type:FETCH_USERS_REQUEST
}
}
const fetchUserSuccess = users => {
console.log("asdfghjk",users);
return{
type: FETCH_USERS_SUCCESS,
payload: users
}
}
const fetchUserFailure = error =>{
return {
type: FETCH_USERS_FAILURE,
payload: error
}
}
const reducer = (state= initialState, action) =>{
switch(action){
case FETCH_USERS_REQUEST :
return{
...state,
loading:true
}
case FETCH_USERS_SUCCESS:
return{
loading:false,
users: action.payload,
error:''
}
case FETCH_USERS_FAILURE:
return{
loading:false,
users:[],
error: action.payload
}
default: return state;
}
}
/**
* takes a parameter dispatch
* @returns a function, as a thunk middleware action creator it returns a function instead of action
*/
const fetchUsers =() =>{
return function(dispatch) {
dispatch(fetchUsersRequest());
axios.get('https://jsonplaceholder.typicode.com/users')
.then((response)=>{
//response.data is the array of users
const users = response.data.map(user => user.id);
// console.log("users====>",users);
dispatch(fetchUserSuccess(users));
})
.catch((error)=>{
// error.message is the error descriptions
let errorMessage = error.message;
dispatch(fetchUserFailure(errorMessage));
})
}
}
const store = createStore(reducer , applyMiddleWare(thunkMiddleWare));
store.subscribe(()=>{console.log("state===>", store.getState())});
store.dispatch(fetchUsers())
Below I’m providing the logs
asdfghjk
state===> { loading: false, users: [], error: '' }
asdfghjk [
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
]
state===> { loading: false, users: [], error: '' }
You can see the state is not updated even after getting the user data and on action FETCH_USERS_REQUEST, loading is still false, I’m not able to understand what is the issue? can anyone help me to fix this issue?