Benjamin Li
Benjamin Li

Reputation: 1697

In Redux, replace dispatch in action creator

Given my action creator:

export const REQUEST_ARTICLES = 'REQUEST_ARTICLES'
export const RECEIVE_ARTICLES = 'RECEIVE_ARTICLES'
export const CHANGE_PAGE = 'CHANGE_PAGE'

export const changePage = (currentPage) => ({
    type: CHANGE_PAGE,
    currentPage,
})

export const requestArticles = () => ({
    type: REQUEST_ARTICLES,
})

export const receiveArticles = json => ({
    type: RECEIVE_ARTICLES,
    posts: json.hits,
})

export const fetchArticles = () => async (dispatch) => {
    try {
        await dispatch(requestArticles())
        let response = await fetch('www.abc.com')
        let json = await response.json()
        await dispatch(receiveArticles(json))
    } catch (e) {
        console.log('error:', e)
    }
}

So I am using dispatch inside action creator. But if I have to dispatch multiple actions, then my code would be

        try {
            await dispatch(requestArticles1())
            await dispatch(requestArticles2())
            await dispatch(requestArticles3())
            await dispatch(requestArticles4())
            await dispatch(requestArticles5())
            let response = await fetch('www.abc.com')
            let json = await response.json()
            await dispatch(receiveArticles(json))
        } catch (e) {
            console.log('error:', e)
        }

I already use mapDispatchToProps in the component. Is there any similar way/method I can use in action creator so that I don't have to dispatch actions manually one by one?

Upvotes: 0

Views: 487

Answers (1)

Alex Young
Alex Young

Reputation: 4039

redux's store.dispatch() is not an asynchronous function, so there is no need to await its return. It will still work because awaiting non-async functions casts them to an immediately-resolving promise.

With regard to dispatching multiple actions, you will need to manually dispatch every action that you need. The question becomes: why do you need to dispatch so many actions? In general for an ajax-calling thunk you will use a started, succeeded and failed action, and not many more.

export const fetchArticles = () => async (dispatch) => {
    try {
        dispatch(requestArticlesStarted())
        const response = await fetch('www.abc.com')
        const json = await response.json()
        dispatch(requestArticlesSucceeded(json))
    } catch (e) {
        console.log('error:', e);
        dispatch(requestArticlesFailed(e));
    }
}

Upvotes: 1

Related Questions