javascriptnode.jsreduxaxiosreact-thunk

Redux thunk middleware does not give the required output


I am new to Redux and am learning redux from here.
I followed through till video 13 and all the examples worked fine.
However, I am unable to get the desired (or any output) for the code shown in video number 13
File: asyncActions.js
Code:

const redux = require('redux')
const axios = require('axios')
const thunkMiddleware = require('redux-thunk').default  

const createStore = redux.createStore
const applyMiddleware = redux.applyMiddleware

const appState = {
    isLoading: 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 fetchUsers = () => {
    return function(dispatch) {
        dispatch(fetchUsersRequest())
        axios.get('https://jsonplaceholder.typicode.com/users')
        .then(response => {
            const users = response.data.map(user => user.id)
            dispatch(fetchUsersSuccess(users))
        })
        .catch(error => {
            dispatch(fetchUsersFailure(error))
        })
    }
}

const reducer = (state = appState, action) => {
    switch (action.type) {
        case FETCH_USERS_REQUEST:
            return {
                ...state,
                isLoading: true,
            }

        case FETCH_USERS_SUCCESS:
            return {
                ...state,
                isLoading: false,
                users: action.payload,
                error: '',
            }
            
        case FETCH_USERS_FAILURE:
            return {
                ...state,
                users: [],
                isLoading: false,
                error: action.payload,
            }   
    
        default:
            break;
    }
}

const store = createStore(reducer, applyMiddleware(thunkMiddleware))
const unSubscribe = store.subscribe(() = { console.log(store.getState()) })
store.dispatch(fetchUsers())
unsubscribe() // this statement is not in the tutorial, but I inferred it from the overall tutorial (please tell me if it is required though)

Expected Output:

{ loading: true, users: [], error: '' }
{ loading: false,
  users: [ 1,2,3,4,5,6,7,8,9,10 ],
  error: '' }

Actual Output:


Screenshot:

screenshot of the actual output

What have I missed?


Solution

  • store.subscribe(() => { console.log(store.getState()) }) you have missed > in your subscribe.