redux-api-middleware-actions
v0.0.3
Published
Strongly typed action creator functions for redux-api-middleware and similar
Downloads
2
Maintainers
Readme
redux-api-middleware-actions
Action creators for https://github.com/agraboso/redux-api-middleware or the like.
This library is optimised for redux projects using TypeScript.
It is inspired heavily by https://github.com/vgmr/redux-helper.
Installation
npm i redux-api-middleware-actions --save
or
yarn add redux-api-middleware-actions
Usage
Assuming you have already set up your api middleware (in this example https://github.com/agraboso/redux-api-middleware
In action creators
import { createApiAction } from 'redux-typed-async-actions';
import { CALL_API } from 'redux-api-middleware';
export const fetchClients = createApiAction<{}, IClientModel[]>('CLIENTS_FETCH', {
CALL_API,
method: 'GET',
endpoint: `/api/clients`,
});
The CALL_API
is the name of the signature property or symbol used for your API middleware.
export const createClient = createApiAction<IClientModel, {}>('CLIENT_CREATE', {
CALL_API,
method: 'POST',
endpoint: `/api/clients`,
});
The two generic parameters are the payload and the response types.
The payload is the parameter passed to the function e.g.
dispatch(createClient({
name: 'Bob the Builder',
}));
You can also pass a function instead of an object as the second parameter. This function can take the payload as an argument.
export const fetchClients = createApiAction<{ name: string }, IClientModel[]>('FETCH_CLIENTS', ({name}) => ({
CALL_API,
method: 'POST',
endpoint: `/api/clients?name=${name}`,
}));
In Reducers
You can then use action creators themselves to match actions and strongly type the action.payload
(on success
it is the response from the api, of type TResponse
you defined in the action creator).
if (actions.fetchClients.matchesSuccess(action)) {
return {
...state,
list: action.payload,
};
} else if (actions.fetchClients.matchesPending(action)) {
...
} else if (actions.fetchClients.matchesFailure(action)) {
...
}