Code Monkey home page Code Monkey logo

hard-reducer's Introduction

hard-reducer

CircleCI Greenkeeper badge

Type friendly facade for better reducer.

npm install hard-reducer --save
# or
yarn add hard-reducer

Concepts

  • Type safe interface
  • Avoid redundant type string definitions
  • Keep reducer interface (State, Action) => State to use with redux.combineReducers()
  • Handle Flux Standard Action <Payload>{ type: string, payload: Payload }

Check this code to know detail.

Flow playground

Examples

This code is runnable in both flowtype and typescript

/* @flow */
// ^ flow magic comment to activate. It will be ignored in typescript.
import {
  buildActionCreator,
  createReducer,
  type ActionCreator
} from "hard-reducer";
// ^ If you use typescript, Do not use `type` before ActionCreator
const { createAction } = buildActionCreator({ prefix: "counter/" });

// Add type to your payload by ActionCreator
const inc: ActionCreator<number> = createAction("inc");
// or infer by function result
const dec = createAction("dec", (val: number) => val);

inc(1); //=> { type: 'counter/inc', payload: 1 }

// Define state type
type State = { value: number };
const initialState: State = { value: 0 };

const reducer = createReducer(initialState)
  // Handle `(State, Payload) => State` in matched context.
  .case(inc, (state, payload) => {
    return {
      value: state.value + payload
    };
  })
  .case(dec, (state, payload) => {
    // $ExpectError
    const p: string = payload;
    return {
      value: state.value - payload
    };
  })
  // Take string
  .case("other/noop", (state, payload) => {
    return state;
  })
  // Take all uncaught action, not payload!
  .else((state, action) => {
    console.log("default fallback");
    return state;
  });

// Use it
const ret0 = reducer(initialState, inc(3));
const ret1 = reducer(ret1, dec(1));

See detail in index.js.flow or index.d.ts

Handle async action: createAsyncAction

createAsyncAction(...) returns { resolved, rejected, started } and callable method.

(You need to add redux-thunk in store's middlewares)

/* @flow */
import { createReducer, buildActionCreator } from "hard-reducer";
const { createAsyncAction } = buildActionCreator();

const incAsync = createAsyncAction("inc-async", async (val: number) => {
  if (val % 2 === 1) {
    throw new Error("error");
  }
  return {
    p: 1
  };
});

type Status = "ready" | "started" | "resolved" | "rejected";
type State = { status: Status, payload: ?{ p: number } };

const reducer = createReducer({ status: "ready", payload: null })
  .case(incAsync.started, state => {
    return { state: "started" };
  })
  .case(incAsync.resolved, (state, payload) => {
    return { state: "resolve", payload };
  })
  .case(incAsync.rejected, (state, error) => {
    return { state: "ready", payload: null };
  });

// store
import reduxThunk from "redux-thunk";
import { applyMiddleware, createStore } from "redux";
const store = createStore(reducer, undefined, applyMiddleware(reduxThunk));
store.subscribe((...args) => {
  console.log("store", store.getState());
});

// dispatch
store.dispatch(incAsync(1));

Handle thunk action: createThunkAction

createThunkAction(...) returns { resolved, rejected, started } and callable method.

(You need to add redux-thunk in store's middlewares)

import { createReducer, buildActionCreator } from "hard-reducer";
const { createThunkAction, createAction } = buildActionCreator();

const inc = createAction("inc", (val: number) => val);

const thunked = createThunkAction(
  "thunked",
  async (input, dispatch, getState) => {
    dispatch(inc(input.value));
    return { ret: true };
  }
);

// Handle
createReducer({ status: "ready", payload: null })
  .case(thunked.started, state => {
    return { state: "started", payload: null };
  })
  .case(thunked.resolved, (state, payload) => {
    return { state: "resolve", payload };
  })
  .case(thunked.rejected, (state, error) => {
    return { state: "ready", payload: null };
  });

// dispatch
store.dispatch(thunked({ value: 1 }));

Related projects

ChangeLog

See ChangeLog.md

LICENSE

MIT

hard-reducer's People

Contributors

greenkeeper[bot] avatar hachibeedi avatar horiuchi avatar mizchi avatar yuki-yano 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

hard-reducer's Issues

Make actionCreator's `type` public

First of all, thanks for an awesome library. This is so helpful to work with.

This might just be my idea but I want to get the action type of an actionCreator (which is now defined as _t) to use in middleware (e.g. redux-saga). typescript-fsa makes it public.
How about making it public for middleware?

An in-range update of react-redux is breaking the build 🚨

The devDependency react-redux was updated from 6.0.0 to 6.0.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

react-redux is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

Release Notes for v6.0.1

This is a minor release with support for react-hot-loader and a few small bug fixes for edge cases.

While you're here, please stop by #1177 to see our roadmap for the next versions of React Redux. We are aware that performance is not so hot in 6.0. Short version: We put too much traffic on React's context API, which isn't really designed for high levels of reads and writes. We're looking to reduce that load and get performance back on track in a minor release, so there won't be backwards compatibility concerns. We have a new extensive benchmark suite to keep us on track and ensure we're not regressing on speed in the future.

And yes, we know about Hooks. Check out #1179.

Changes

Commits

The new version differs by 35 commits.

  • 162b81a 6.0.1
  • d8a7ab5 Update build deps. Add React 16.8 tests.
  • 6ad2b55 Remove --save option as it isn't required anymore (#1193)
  • fac9ad1 Update Provider.md and quick-start.md (#1182)
  • 9bf2375 Update Provider.md
  • fcd5ed8 Update Provider.md
  • c198249 Update react-router usage example (#1180)
  • ab77450 Upgrade to react-is v16.7.0 (#1174)
  • 0bf4e1f Remove duplicate line in connect api documents (#1173)
  • 6e0a106 Updated: Support React-Hot-Loader compatibility (#1168)
  • 63af52f Update accessing-store.md (#1163)
  • 5199d9d Ensure that component prop 'context' really contains a React context … (#1134)
  • e7661b3 Fix spacing issues (#1153)
  • 75b90f9 Add / change docs about v6 (#1148)
  • 5088345 Add connect() API doc (#1140)

There are 35 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

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.