Skip to content

Throw error when custom action creator does not have type value #3570

@chawes13

Description

@chawes13

It'd be great to have a guard for passing in an action creator that doesn't have a truthy type string value.

I encountered this issue when migrating over to RTK. We built some custom action creators that we use in combination with a custom api middleware (we're not ready to switch to RTQ just yet - baby steps 😅!). While these have the toString() override, the builder addCase method is not using that and it seems like this override is getting deprecated in v2.

The following led to a fairly subtle bug, since it fails silently.

extraReducers: (builder) => {
  builder.addCase(apiActions.fetchTodo, todoHandler) // fetchTodo.type === undefined
}

Since I'm working in JS, this issue is easier to run into. Although, I believe a guard may still be helpful to prevent accidental assignments of an empty string to the type attribute in the implementation of a custom action creator in TS.

const type =
typeof typeOrActionCreator === 'string'
? typeOrActionCreator
: typeOrActionCreator.type
if (type in actionsMap) {
throw new Error(
'addCase cannot be called with two reducers for the same action type'
)
}
actionsMap[type] = reducer
return builder

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions