简体   繁体   中英

What redux-thunk offer for async call?

I am just getting familiar with redux and redux-thunk . I tried the below snippet to work with the async call, with redux and redux-thunk .

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

const createStore = redux.createStore;
const applyMiddleware = redux.applyMiddleware;
const accessPoint = axios.create({
    baseURL: 'https://jsonplaceholder.typicode.com/',
    responseType: 'json',
    headers: {
        'Accept-Encoding': '',
    },
});

const FETCH_USER_PENDING = 'FETCH_USER_PENDING';
const FETCH_USER_FULFILLED = 'FETCH_USER_FULFILLED';
const FETCH_USER_REJECTED = 'FETCH_USER_REJECTED';

const initialState = {
    isLoading: false,
    users: [],
    error: '',
}

const fetchUserPending = () => {
    return {type: FETCH_USER_PENDING}
}
const fetchUserFulfilled = data => {
    return {type: FETCH_USER_FULFILLED, payload: data}
}
const fetchUserRejected = errorMessage => {
    return {type: FETCH_USER_REJECTED, payload: errorMessage}
}

const reducer = (state = initialState, action) => {
    const {type, payload} = action;
    switch(type){
        case FETCH_USER_PENDING: {
            return {
                ...state,
                isLoading: true,
            }
        }
        case FETCH_USER_FULFILLED: {
            return {
                isLoading: false,
                users: payload,
                error: ''
            }
        }
        case FETCH_USER_REJECTED: {
            return {
                isLoading: false,
                users: [],
                error: payload
            }
        }
        default: return state;
    }
}

const fetchUsers = () => {
    return function(dispatch){
        dispatch(fetchUserPending());
        accessPoint.get('users')
            .then(response => {
                dispatch(fetchUserFulfilled(response.data.map(user => user.name)))
            })
            .catch(error => {
                dispatch(fetchUserRejected(error.message));
            })
    }
}

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

store.dispatch(fetchUsers());

Code On CodeSandBox

This works absolutely fine and gives the expected output.

Also tried the same example without thunk and some changes,

const redux = require('redux');
const axios = require('axios');

const createStore = redux.createStore;
const accessPoint = axios.create({
    baseURL: 'https://jsonplaceholder.typicode.com/',
    responseType: 'json',
    headers: {
        'Accept-Encoding': '',
    },
});

const FETCH_USER_PENDING = 'FETCH_USER_PENDING';
const FETCH_USER_FULFILLED = 'FETCH_USER_FULFILLED';
const FETCH_USER_REJECTED = 'FETCH_USER_REJECTED';

const initialState = {
    isLoading: false,
    users: [],
    error: '',
}

const fetchUserPending = () => {
    return {type: FETCH_USER_PENDING}
}
const fetchUserFulfilled = data => {
    return {type: FETCH_USER_FULFILLED, payload: data}
}
const fetchUserRejected = errorMessage => {
    return {type: FETCH_USER_REJECTED, payload: errorMessage}
}

const reducer = (state = initialState, action) => {
    const {type, payload} = action;
    switch(type){
        case FETCH_USER_PENDING: {
            return {
                ...state,
                isLoading: true,
            }
        }
        case FETCH_USER_FULFILLED: {
            return {
                isLoading: false,
                users: payload,
                error: ''
            }
        }
        case FETCH_USER_REJECTED: {
            return {
                isLoading: false,
                users: [],
                error: payload
            }
        }
        default: return state;
    }
}

const fetchUsers = (dispatch) => {
    dispatch(fetchUserPending());
    accessPoint.get('users')
        .then(response => {
            dispatch(fetchUserFulfilled(response.data.map(user => user.name)))
        })
        .catch(error => {
            dispatch(fetchUserRejected(error.message));
        })
}

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

fetchUsers(store.dispatch);

Code On CodeSandBox

Here instead of passing function to store.dispatch() with a react-thunk , I am passing store.dispatch to fetchUsers() function. And depending on the stages I am dispatching actions to it.

Confusing is what redux-thunk offers with the async call when both snippets(one using redux-thunk and one without it) produce exact same output (not overall difference but with the above scenario).

If something is wrong with practicing such code, please correct it.

Advance thank you for your input.

Redux middleware system and redux-thunk middleware provide a way to express asynchronous actions in a concise manner.

  1. You don't need to pass store.dispatch and store.getState every time when calling the action creator. The Redux applyMiddleware API does it for you.

  2. You can also Injecting Config Values Into Thunks using the withExtraArgument() API of redux-thunk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM