Git Product home page Git Product logo

typed-actions's Introduction

typed-actions

Travis branch npm version npm license

Some Types and Utils (based on redux-actions way) to create type-safe actions, reducers, and epics with auto-inferred types.

Main points:

  • 100% Flow coverage for the redux-side with minimum typings (auto-inferred types) and less boilerplate
  • Safe types and functions, which help to reduce risks for Type mistakes
  • Accurate Type-errors handling
  • Deep immutable Type (Frozen) for actions and redux state
  • Immer support

Installation

npm install typed-actions

Usage

You can get some examples here with explanations.

Actions

Actions are compatible with Flux Standard Action

  • action(payload, ?meta) produces {type, payload} | {type, payload, meta}
  • error(payload, ?meta) produces {type, payload, error: true} | {type, payload, meta, error: true}
  • empty() produces {type}
import {createActions, action, empty} from 'typed-actions'
import type {EntityId} from '../types';

/**
 * Declare Action Types as constants and export them
 */
export const UPDATE = '@namespace/UPDATE'
export const UPDATE_FULFILLED = '@namespace/UPDATE_FULFILLED'
export const UPDATE_FAILED = '@namespace/UPDATE_FAILED'

/**
 * Create Actions Collection
 */
const actions = createActions({
    /**
     * {type: UPDATE}
     */
    [UPDATE]: empty,
    /**
     * {type: UPDATE_FULFILLED, payload: EntityId[]}
     */
    [UPDATE_FULFILLED]: (x: EntityId[]) => action(x),
    /**
     * {type: UPDATE_FAILED, payload: EntityId, meta: {sync: true}}
     */
    [UPDATE_FAILED]: (x: EntityId) => action(x, {sync: true}),
})

/**
 * Export Action Creators
 */
export const {
    [UPDATE]: update,
    [UPDATE_FULFILLED]: updateFulfilled,
    [UPDATE_FAILED]: updateFailed,
} = actions

/**
 * Export Collection Type
 */
export type Actions = typeof actions

You might find this declaration style more readable:

let actions

export const {
    [UPDATE]: update,
    [UPDATE_FULFILLED]: updateFulfilled,
    [UPDATE_FAILED]: updateFailed,
} = actions = createActions({
    [UPDATE]: empty,
    [UPDATE_FULFILLED]: (x: EntityId[]) => action(x)
    [UPDATE_FAILED]: (x: EntityId) => action(x, {sync: true}),
})

export type Actions = typeof actions

Reducers

import {handleActions, type Handlers, type Frozen} from 'typed-actions';
import type {EntityId} from '../types';

/**
 * Import action types with Actions Collection Type
 */
import {
    type Actions,
    UPDATE,
    UPDATE_FULFILLED,
    UPDATE_FAILED,
} from './actions';

/**
 * Declare State for the reducer
 */
export type State = {
    data: EntityId[],
    status: 'done' | 'pending' | 'failed',
};

/**
 * Use Handlers Type for the type-casting.
 * This way functions will get right arguments Types
 */
export default handleActions(({
    /**
     * No need to point the State Type in arguments,
     * it would be auto-inferred Deep Immutable Type of State
     */
    [UPDATE]: state => ({
        ...state,
        status: 'pending',
    }),

    /**
     * The second argument (action) will also have the right type
     * {type: UPDATE_FULFILLED, payload: EntityId[]}
     */
    [UPDATE_FULFILLED]: (state, {payload}) => ({
        ...state,
        data: payload,
        status: 'done',
    }),

    [UPDATE_FAILED]: state => ({
        ...state,
        status: 'failed',
    }),
}: Handlers<State, Actions>));

Immer

You can use immer for immutable state modifying.

Note that handler accepts 3 arguments: draft state (for changes), action and current state.

import { type Handlers, handleActions } from 'typed-actions/immer'
import type {EntityId} from '../types';

import {
    type Actions,
    UPDATE,
    UPDATE_FULFILLED,
    UPDATE_FAILED,
} from './actions';

export type State = {
    data: EntityId[],
    status: 'done' | 'pending' | 'failed',
};

export default handleActions(({
    [UPDATE]: state => {
        state.status = 'pending'
    },

    [UPDATE_FULFILLED]: (state, {payload}) => {
        state.data = payload
        state.status = 'done'
    },

    [UPDATE_FAILED]: state => {
        state.status = 'failed'
    },
}: Handlers<State, Actions>));

Epics

If you're using redux-observable, this Epic Type could be useful.

import type {Epic} from 'typed-actions/redux-observable';

import {
    type Actions,
    UPDATE_FULFILLED,
    anotherOneAction,
} from './actions';

import {type State} from './reducers';

export const updateEpic: Epic<State, Actions> = action$ => action$
    .ofType(UPDATE_FULFILLED)
    /**
     * No need to add types here, action would be the right Type out of the box
     */
    .map(action => anotherOneAction(action.payload));

export const unionEpic: Epic<State, Actions> = action$ => action$
    .ofType(UPDATE, UPDATE_FULFILLED)
    /**
     * {type: UPDATE} | {type: UPDATE_FULFILLED, payload: EntityId[]}
     */
    .map(action => {
        if (action.type === UPDATE_FULFILLED) {
            /**
             * Type Refinement will work as well
             *
             * {type: UPDATE_FULFILLED, payload: EntityId[]}
             */
            console.log(action.payload)
        }
    });

Just to note, if you're using dependencies in epics, you can pass its type in as the third argument.

type Dependencies = {api: () => void}

export const epic: Epic<State, Actions, Dependencies> = action$ => action$

The recommended way is to redeclare your own Epic type with custom dependencies and use it, like:

// types.js
import type {Epic} from 'typed-actions/redux-observable'

type Dependencies = {api: () => void}

export type Epic<S, A, D = Dependencies> = Epic<S, A, D>

// epics.js
import type {Epic} from './types'

export const epic: Epic<State, Actions> = action$ => action$

typed-actions's People

Contributors

antonk52 avatar dependabot[bot] avatar lttb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

typed-actions's Issues

createAction doesn't support Symbol type

We are trying to use typed-actions in our project but according to our code style, we are using symbols everywhere. It would be good if type-actions will support this use case.

Flow error on flow version 113

I'm running into the following flow errors when running on version 113. Similar code on another repo with version 84 is passing just fine.

yarn run v1.22.4
$ flow
Error ------------------------------------------------------------- node_modules/typed-actions/types/index.js.flow:60:35

Missing type annotation for `A`. `A` is a type parameter declared in function type [1] and was implicitly instantiated
at `$ObjMap` [2].

   node_modules/typed-actions/types/index.js.flow:60:35
                                         v-----------------------------
   60| export type Actions<Collection> = $ObjMap<$ObjMapi<Collection, <
   61|   K, V, R, A, B, C,
   62| >(K, V) => $Call<
   63|   & (((...args: [A, B, C]) => R) => (A, B, C) => Action<K, R>)
   64|   & (((...args: [A, B]) => R) => (A, B) => Action<K, R>)
   65|   & (((...args: [A]) => R) => (A) => Action<K, R>)
   66| , V>>, typeof locate>
       --------------------^ [2]

References:
   node_modules/typed-actions/types/index.js.flow:30:24
                              v----------------------
   30| declare function locate<A, B, C, D, E, F, R>((
   31|   A | (B & void),
   32|   C | (D & void),
   33|   E | (F & void),
   34| ) => R): ((
   35|   A | (void & null & empty),
   36|   C | (void & null & empty),
   37|   E | (void & null & empty),
   38| ) => R)
       -----^ [1]


Error ------------------------------------------------------------- node_modules/typed-actions/types/index.js.flow:60:35

Missing type annotation for `C`. `C` is a type parameter declared in function type [1] and was implicitly instantiated
at `$ObjMap` [2].

   node_modules/typed-actions/types/index.js.flow:60:35
                                         v-----------------------------
   60| export type Actions<Collection> = $ObjMap<$ObjMapi<Collection, <
   61|   K, V, R, A, B, C,
   62| >(K, V) => $Call<
   63|   & (((...args: [A, B, C]) => R) => (A, B, C) => Action<K, R>)
   64|   & (((...args: [A, B]) => R) => (A, B) => Action<K, R>)
   65|   & (((...args: [A]) => R) => (A) => Action<K, R>)
   66| , V>>, typeof locate>
       --------------------^ [2]

References:
   node_modules/typed-actions/types/index.js.flow:30:24
                              v----------------------
   30| declare function locate<A, B, C, D, E, F, R>((
   31|   A | (B & void),
   32|   C | (D & void),
   33|   E | (F & void),
   34| ) => R): ((
   35|   A | (void & null & empty),
   36|   C | (void & null & empty),
   37|   E | (void & null & empty),
   38| ) => R)
       -----^ [1]


Error ------------------------------------------------------------- node_modules/typed-actions/types/index.js.flow:60:35

Missing type annotation for `E`. `E` is a type parameter declared in function type [1] and was implicitly instantiated
at `$ObjMap` [2].

   node_modules/typed-actions/types/index.js.flow:60:35
                                         v-----------------------------
   60| export type Actions<Collection> = $ObjMap<$ObjMapi<Collection, <
   61|   K, V, R, A, B, C,
   62| >(K, V) => $Call<
   63|   & (((...args: [A, B, C]) => R) => (A, B, C) => Action<K, R>)
   64|   & (((...args: [A, B]) => R) => (A, B) => Action<K, R>)
   65|   & (((...args: [A]) => R) => (A) => Action<K, R>)
   66| , V>>, typeof locate>
       --------------------^ [2]

References:
   node_modules/typed-actions/types/index.js.flow:30:24
                              v----------------------
   30| declare function locate<A, B, C, D, E, F, R>((
   31|   A | (B & void),
   32|   C | (D & void),
   33|   E | (F & void),
   34| ) => R): ((
   35|   A | (void & null & empty),
   36|   C | (void & null & empty),
   37|   E | (void & null & empty),
   38| ) => R)
       -----^ [1]


Error ------------------------------------------------------------- node_modules/typed-actions/types/index.js.flow:60:43

Missing type annotation for `K`. `K` is a type parameter declared in function type [1] and was implicitly instantiated
at `$ObjMapi` [2].

   node_modules/typed-actions/types/index.js.flow:60:43
                                                 v---------------------
   60| export type Actions<Collection> = $ObjMap<$ObjMapi<Collection, <
   61|   K, V, R, A, B, C,
   62| >(K, V) => $Call<
   63|   & (((...args: [A, B, C]) => R) => (A, B, C) => Action<K, R>)
   64|   & (((...args: [A, B]) => R) => (A, B) => Action<K, R>)
   65|   & (((...args: [A]) => R) => (A) => Action<K, R>)
   66| , V>>, typeof locate>
       ----^ [2]

References:
   node_modules/typed-actions/types/index.js.flow:60:64
                                                                      v
   60| export type Actions<Collection> = $ObjMap<$ObjMapi<Collection, <
   61|   K, V, R, A, B, C,
   62| >(K, V) => $Call<
   63|   & (((...args: [A, B, C]) => R) => (A, B, C) => Action<K, R>)
   64|   & (((...args: [A, B]) => R) => (A, B) => Action<K, R>)
   65|   & (((...args: [A]) => R) => (A) => Action<K, R>)
   66| , V>>, typeof locate>
       ---^ [1]


Error ------------------------------------------------------------- node_modules/typed-actions/types/index.js.flow:60:43

Missing type annotation for `R`. `R` is a type parameter declared in function type [1] and was implicitly instantiated
at `$ObjMapi` [2].

   node_modules/typed-actions/types/index.js.flow:60:43
                                                 v---------------------
   60| export type Actions<Collection> = $ObjMap<$ObjMapi<Collection, <
   61|   K, V, R, A, B, C,
   62| >(K, V) => $Call<
   63|   & (((...args: [A, B, C]) => R) => (A, B, C) => Action<K, R>)
   64|   & (((...args: [A, B]) => R) => (A, B) => Action<K, R>)
   65|   & (((...args: [A]) => R) => (A) => Action<K, R>)
   66| , V>>, typeof locate>
       ----^ [2]

References:
   node_modules/typed-actions/types/index.js.flow:60:64
                                                                      v
   60| export type Actions<Collection> = $ObjMap<$ObjMapi<Collection, <
   61|   K, V, R, A, B, C,
   62| >(K, V) => $Call<
   63|   & (((...args: [A, B, C]) => R) => (A, B, C) => Action<K, R>)
   64|   & (((...args: [A, B]) => R) => (A, B) => Action<K, R>)
   65|   & (((...args: [A]) => R) => (A) => Action<K, R>)
   66| , V>>, typeof locate>
       ---^ [1]



Found 5 errors
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

The code that I am adding that is triggering the issue is as follows:

// @flow
import { action, createActions, handleActions } from 'typed-actions';

const LOAD_THREAD_DATA = '@threads/LOAD_THREAD_DATA';

const actions = createActions({
  [LOAD_THREAD_DATA]: (threadId: string) => action({ threadId }),
});

type Actions = typeof actions;

export const loadThreadData = actions[LOAD_THREAD_DATA];

I'll probably take a stab at seeing if I can correct the flowtypes (if that is actually the issue) but it's a bit over my head.

How to extract flow type of an action from an action creator?

Hi @lttb.
Thanks for the awesome wrapper for redux-actions.

I have a question.
In my current project, i use redux-saga and i want to add a type of the received action.
I do it something like this:

type ReceivedAction<F> = $Call<F, *>;

export function* worker(
  action: ReceivedAction<typeof change>
): Saga<*> {
  // ...
}

But maybe you have a much better suggestion for this?
Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.