Skip to content

Strongly typed action creator functions for redux-api-middleware and similar

Notifications You must be signed in to change notification settings

christensena/redux-api-middleware-actions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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)) {
    ...
  }

About

Strongly typed action creator functions for redux-api-middleware and similar

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published