rochellecanale
rochellecanale

Reputation: 149

return function doesn't return anything using async redux process

I am following this tutorial regarding redux async request https://youtu.be/z2XCUu2wIl0 but when I tried to run the script using node asyncActions.js it doesn't return any value. I tried to debug this by adding a simple console log inside and it doesn't appear. There are no error in the console also that's why I am having a hard time debugging this.

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 = () => {

    console.log('here');

    return function(dispatch) {

        console.log('inside'); // not showing

        dispatch(fetchUsersRequest());

        axios.get('https://jsonplaceholder.typicode.com/users')
        .then(response => {
            //response.data
            const users = response.data.map(user => user.id)
            dispatch(fetchUsersSuccess(users))
        }).catch(error => {
            //error.message
            dispatch(fetchUsersFailure(error.message))
        })
    }

}

const store = createStore(reducer, applyMiddleware(thunkMiddleware)); 
store.subscribe(() => { console.log(store.getState())});

store.dispatch(fetchUsers); // call the API

Upvotes: 0

Views: 35

Answers (1)

phry
phry

Reputation: 44086

I already wrote in a comment that this is a terribly outdated way of writing Redux and you should switch to an up-to-date tutorial.

As what's wrong with your code here:

You need to execute the fetchUsers thunk action creator before dispatching it, so do

store.dispatch(fetchUsers());

Upvotes: 1

Related Questions