Search code examples
javascriptreactjsreduxreact-reduxredux-thunk

Is it necessary for action creators to return an action ?


I have an action creator which takes in an id and a callback function. It sends a request to server to do some stuff and returns a dummy action. All I want to do here is call the callback function and exit, because that dummy action has no use to me for example liking a post. I just need the server to know that a user liked a post, I don't some state changes, I can change the like button state via callback. So my question is do we require an action creator to return an action. Here is my code

export const deleteProduct = (id,cb) => async (dispatch) => {
   let res = await axios.delete(`${BASE_URL}/api/v1/product/${id}`,
                   {withCredentials:true})
   cb();
    dispatch({type: DUMMY, payload : res.data});       
};

After I am deleting a product I can just hide that product from list when the callback is fired. Do I need to call the dispatch explicitly or is it optional. ? I am using Redux-thunk for handling axios promises.


Solution

  • In redux-thunk dispatching is completely optional. In fact, one of it's main motivations is to provide conditional dispatches.

    So yeah, you can totally just do:

    export const deleteProduct = (id,cb) => async () => {
       let res = await axios.delete(`${BASE_URL}/api/v1/product/${id}`,
                       {withCredentials:true})
       cb();    
    };
    

    However, I believe this is breaking one of the main concepts of redux, which is unidirectional data flow. The concept is that the data should only flow in one direction. The view dispatches an action to update the store to trigger render to update the view. The view should not dispatch and action and rerender from the result.

    Basically, If you want to hide the item from the list after it is deleted, instead of doing this in a callback, you should dispatch an action to update the data in the store and let react-redux rerender the component without the deleted item in it.