redux-act
redux-act copied to clipboard
TypeScript: an action with a function with no arguments as payload causes a typing error
Greetings to friends, I really like the library, but I ran into such a problem that if you pass a function without arguments as payload, an error occurs:
Expected 1 arguments, but got 0. TS2554
example:
export const logoutRequest = createAction('auth/LOGOUT_REQUEST', api.logout)
. . .
// api.ts
logout: () => ({
request: {
method: 'PUT',
url: endpoints.LOGOUT_API,
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
Authorization: `Bearer ${getToken()}`,
},
},
})
We use middleware redux-axios-middleware, which sends a request if payload has a request property, such as our logout
If you try to call action logoutRequest, there will be an error Expected 1 arguments, but got 0. TS2554
But our logout method does not accept a single argument, how to fix it?
If you just transfer an empty object when calling, then everything works correctly:
dispatch (logoutRequest ({}))
but it’s not beautiful, I would like to solve the problem
When calling createAction
, 1st argument is the definition / type, while the 2nd is a payload reducer, and not a payload itself. It's a way to pass several argument went creating the action and reducing them into a single payload.
const myAction = createAction('whatever', (x, y, z) => ({x, y, z}));
myAction(1, 2, 3);
// returns {type: '[1] whatever', payload: {x: 1, y: 2, z: 3}}
In you case, you have no arguments to reduce so I'm wondering what you are trying to achieve... if you want your payload to be an object with the request property, you can do something like:
export const logoutRequest = createAction('auth/LOGOUT_REQUEST');
dipatch(logoutRequest(api.logout()));
@pauldijou is this very first argument so necessary? maybe my payload is in the api.logout function, which doesn't need input parameters
I switched from redux-actions, this option worked well there, isn’t it possible for arguments?