javascriptreactjsreduxredux-toolkit

Using Redux-Toolkit slice action with class components via connect HOC, does it require dispatch or not?


I have been working on an older code base with class components using Redux connect HOC. There are few RTK slices introduced before. I am abit confused as to why these 2 ways of using the action from the slice is working correctly (can see in Redux Toolkit that ways update the state and appear in the Actions panel (left hand side).

2 ways:

  1. with dispatch (updateAbc)
  2. without dispatch (updateXyz)

See example below

const mapDispatchToProps = (dispatch) => {
    return {
        updateAbc: (params) => dispatch(updateAbc(params)),
        updateXyz,
    }
}

Both are from the slice file:

const sampleSlice = createSlice({
   name: 'sample',
   initialState: {},
   reducers: {
      updateAbc: () => { /* do something */},
      updateXyz: () => { /* do something */}
   }
})
const { actions, reducer } = sampleSlice
export const {
    updateAbc,
    updateXyz,
} = actions

enter image description here

How come both are working or am I missing something or they are just both valid ways (but I don't see how it dispatches it without the explicit call to dispatch)?


Solution

  • How come both are working or am I missing something or they are just both valid ways (but I don't see how it dispatches it without the explicit call to dispatch)?

    They are both valid ways to decorate the actions in the connectDispatchToProps helper. See the Object Shorthand Form for details. Note that the emphasis is mine.

    mapDispatchToProps may be an object where each field is an action creator.

    import { addTodo, deleteTodo, toggleTodo } from './actionCreators'
    
    const mapDispatchToProps = {
      addTodo,
      deleteTodo,
      toggleTodo,
    }
    
    export default connect(null, mapDispatchToProps)(TodoApp)
    

    In this case, React-Redux binds the dispatch of your store to each of the action creators using bindActionCreators.

    What this means for your code is that updateXyz gets wrapped in a call to dispatch "auto-magically".

    const mapDispatchToProps = (dispatch) => {
      return {
        updateAbc: (params) => dispatch(updateAbc(params)),
        updateXyz, // <-- dispatch bound to action creator
      }
    }
    

    The more typical mapDispatchToProps would be written as follows:

    const mapDispatchToProps = {
      updateAbc,
      updateXyz,
    }