I am trying to learn redux on my own and following different tutorials around the internet. So, far I am doing good and able to understand many things by myself; however, I am stuck on the below code in which I am unable to understand what’s going on:
const redux = require('redux')
const createStore = redux.createStore
const applyMiddleware = redux.applyMiddleware
const thunkMiddleware = require('redux-thunk').default
const axios = require('axios')
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 = () => {
return {
type: FETCH_USERS_REQUEST
}
}
const fetchUsersSuccess = users => {
return {
type: FETCH_USERS_SUCCESS,
payload: users
}
}
const fetchUsersFailure = error => {
return {
type: FETCH_USERS_FAILURE,
payload: error
}
}
const reducer = (state = initialState, action) => {
switch (action.type) {
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
}
}
}
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)
dispatch(fetchUsersSuccess(users))
})
.catch(error => {
// error.message is the error description
dispatch(fetchUsersFailure(error.message))
})
}
}
const store = createStore(reducer, applyMiddleware(thunkMiddleware))
store.subscribe(() => { console.log(store.getState()) })
store.dispatch(fetchUsers())
According to me, it should work but I am getting the below error, also need some help on how to debug the code:
TypeError: middleware is not a function
at E:ReposReduxRawnode_modulesreduxdistcjsredux.cjs:407:51
at Array.map (<anonymous>)
at E:ReposReduxRawnode_modulesreduxdistcjsredux.cjs:407:31
at createStore (E:ReposReduxRawnode_modulesreduxdistcjsredux.cjs:133:33)
at Object.<anonymous> (E:ReposReduxRawasyncActions.js:78:15)
at Module._compile (node:internal/modules/cjs/loader:1369:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1427:10)
at Module.load (node:internal/modules/cjs/loader:1206:32)
at Module._load (node:internal/modules/cjs/loader:1022:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)