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.
npm i redux-api-middleware-actions --save
or
yarn add redux-api-middleware-actions
Assuming you have already set up your api middleware (in this example https://github.com/agraboso/redux-api-middleware
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}`,
}));
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)) {
...
}