I followed the tutorial on typesafe-actions to create the simplest possible TypeScript/Redux project, however I can't get it working. I keep getting the error,
Error: Argument 1 is invalid, it should be an action-creator instance from "typesafe-actions" or action type of type: string | symbol
when I try to visit the page (Typescript is happy though, code transpiles ok)
Here's my reducer.ts (Single reducer, should just overwrite the store with newData). This appears to be where the error is originating from, the second argument to handleAction
import { setData } from "actions";
import { createReducer } from "typesafe-actions";
const dataReducer = createReducer({}).handleAction(
setData,
(state, action) => action.payload.newData
);
export default dataReducer;
Here's the actions.js file (I've tried using both action
and createAction
, no difference):
import { action, createAction } from "typesafe-actions";
import { SET_DATA } from "constants";
export const setData = (newData: string) => action(SET_DATA, { newData });
constants.ts is a simple one-liner,
export const SET_DATA = "SET_DATA";
As per the tutorial, I'm trying to use the fancy "type-free" syntax in my Reducer code, so I also have a types.d.ts
file
// types.d.ts
import { StateType, ActionType } from "typesafe-actions";
export type RootAction = ActionType<typeof import("./actions").default>;
declare module "typesafe-actions" {
interface Types {
RootAction: RootAction;
}
}
As far as I can tell, this should work for a very simple example. What am I doing wrong ere?
Versions FYI:
"react": "^16.13.1",
"redux": "^4.0.5",
"react-redux": "^7.2.1",
"typescript": "~3.7.2"
"typesafe-actions": "^5.1.0"
While this isn't strictly answering your question:
We specifically recommend using our official Redux Toolkit package, rather than typesafe-actions
. RTK is already written in TS and works great in TS apps.
As part of that, RTK will generate correctly typed action creators from the createSlice
function based on the reducers you define.
You can set up a brand new project quickly using our Redux+TS template for Create-React-App, which comes with RTK already configured to set up your store and type your RootState
.
Also, we recommend not trying to follow some of the patterns listed in the typesafe-actions
docs, such as trying to define a union of all possible action types. There's really no serious benefit from that approach.
See the new "Redux Essentials" Redux core docs tutorial for instructions on how to use Redux Toolkit and the React-Redux hooks API the right way, as well as the RTK "Usage with TypeScript" docs page.