Search code examples
reactjsreduxreact-reduxredux-thunk

Redux Action Creator and Dispatch confusion with syntax


I'm having some trouble understanding this productListCreator syntax. Using thunk, the tutorial I'm following says that thunk allows us to write the an async function within a function.

productListCreator is a function that returns async function with dispatch as an argument.

But when you use call/use this with dispatch(productListCreator()), I'm confused.

productListCreator has no dispatch argument being passed. Instead it is being passed into the useDispatch hook.

So to me the code is saying useDispatch() which takes productListCreator function and runs it, which has no argument passed in for "dispatch".

import axios from 'axios'

const productListCreator = () => async(dispatch) => {  
    try {
        dispatch({
            type: 'PRODUCT_LIST_REQUEST'
        })

        const { data } = await axios.get('/api/products')
        
        dispatch({
            type: 'PRODUCT_LIST_SUCCESS',
            payload: data
        }) 
    } catch (error) {
        dispatch({
            type: 'PRODUCT_LIST_ERROR',
            payload: error.message
        })
    }
}


export default productListCreator
const dispatch = useDispatch()
    
    // Retrieve all products at reload
    useEffect(()=>{
        dispatch(productListCreator())
    },[])

Solution

  • productListCreator is a "thunk action creator". It defines the "thunk function", and returns it. That "thunk function" is what gets passed to dispatch. The thunk middleware then intercepts the thunk function, calls it, and passes in (dispatch, getState) as arguments.

    I'd recommend reading through the new "Writing Logic with Thunks" docs page, which explains how thunks work.