<commit_before># redux-loop

[![Build Status](https://travis-ci.org/raisemarketplace/redux-loop.svg?branch=master)](https://travis-ci.org/raisemarketplace/redux-loop)


Sequence your effects naturally and purely by returning them from your reducer.

## Quick Example

```javascript
import { createStore } from 'redux';
import { install, loop, Effects } from 'redux-loop';
import { fromJS } from 'immutable';

const firstAction = {
  type: 'FIRST_ACTION',
};

const doSecondAction = (value) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        type: 'SECOND_ACTION',
        payload: value,
      });
    });
  });
}

const thirdAction = {
  type: 'THIRD_ACTION',
};

// immutable store state allowed by default, but not required
const initialState = fromJS({
  firstRun: false,
  secondRun: false,
  thirdRun: false,
});

function reducer(state, action) {
  switch(action.type) {

  case 'FIRST_ACTION':
    // Enter a sequence at FIRST_ACTION, SECOND_ACTION and THIRD_ACTION will be
    // dispatched in the order they are passed to batch
    return loop(
      state.set('firstRun', true),
      Effects.batch([
        Effects.promise(doSecondAction, 'hello'),
        Effects.constant(thirdAction)
      ])
    );

  case 'SECOND_ACTION':
    return state.set('secondRun', action.payload);

  case 'THIRD_ACTION':
    return state.set('thirdRun', true);

  default:
    return state;
  }
}

const store = install()(createStore)(reducer, initialState);

store
  .dispatch(firstAction);
  .then(() => {
    // dispatch returns a promise for when the current sequence is complete
    // { firstRun: true, secondRun: 'hello', thirdRun: true }
    console.log(store.getState().toJS());
  });
```

## Tutorial

### Install the store enhancer

```javascript
import { createStore } from 'redux';
import reducer from './reducers';
import { install } from 'redux-loop';

const store = install()(createStore)(reducer);
```

Installing `redux-loop` is as easy as installing any other store enhancer. You
can apply it directly over `createStore` or compose it with other enhancers
and middlewares. For best results, we recommend installing this enhancer such
that other enhancers like `devtools` will receive the result of `getState()`
from `redux-loop`.

### Write a reducer with some effects

```javascript
import { Effects } from 'redux-loop';
import { loadingStart, loadingSuccess, loadingFailure } from './actions';

export function fetchDetails(id) {
  return fetch(`/api/details/${id}`)
    .then((r) => r.json())
    .then(loadingSuccess)
    .catch(loadingFailure);
}

export default function reducer(state, action) {
  switch (action.type) {
    case 'LOADING_START':
      return loop(
        { ...state, loading: true },
        Effects.promise(fetchDetails, action.payload.id)
      );

    case 'LOADING_SUCCESS':
      return {
        ...state,
        loading: false,
        details: action.payload
      };

    case 'LOADING_FAILURE':
      return {
        ...state,
        loading: false,
        error: action.payload.message
      };

    default:
      return state;
  }
}
```

Any reducer case can return a `loop` instead of a state object. A `loop` joins
an updated model state with an effect for the store to process. There are
several options for effects, all available under the `Effects` object:

- `promise(factory, ...args)`
  - Accepts a `factory` function that returns a `Promise` for an action
    instance when called with `args`.
- `constant(action)`
  - Accepts an `action` instance to dispatch immediately once the current
    dispatch cycle is completed.
- `batch(effects)`
  - Accepts an array of other effects and runs them in parallel, dispatching
    the resulting actions once all effects are resolved.
- `none()`
  - A no-op action, for convenience when writing custom effect creators

### Easily test reducer results

```javascript
import test from 'tape';
import reducer, { fetchDetails } from './reducer';
import { loadingStart } from './actions';
import { Effects, loop } from 'redux-loop';

test('reducer works as expected', (t) => {
  const state = { loading: false };

  const result = reducer(state, loadingStart(1));

  t.deepEqual(result, loop(
    { loading: true },
    Effects.promise(loadingStart, 1)
  ));
});
```

Effects are declarative specifications of the next behavior of the store. They
are only processed by an active store, pushing effecting behavior to the edge of
the application. You can call a reducer as many times with a given action and
state and always get a result which is `deepEqual`.

> CAVEAT
> For testing sanity, always pass a referenceable function to `Effects.promise`.
> Functions curried or bound from the same function with the same arguments are
> not equal within JavaScript, and so are best to avoid if you want to compare
> effects in your tests.

### Use the custom `combineReducers` if you need it

```javascript
import { createStore } from 'redux';
import { combineReducers, install } from 'redux-loop';

import { firstReducer, secondReducer } from './reducers';

const reducer = combineReducers({
  first: firstReducer,
  second: secondReducer,<commit_msg>fix readme typo<commit_after># redux-loop

[![Build Status](https://travis-ci.org/raisemarketplace/redux-loop.svg?branch=master)](https://travis-ci.org/raisemarketplace/redux-loop)


Sequence your effects naturally and purely by returning them from your reducer.

## Quick Example

```javascript
import { createStore } from 'redux';
import { install, loop, Effects } from 'redux-loop';
import { fromJS } from 'immutable';

const firstAction = {
  type: 'FIRST_ACTION',
};

const doSecondAction = (value) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        type: 'SECOND_ACTION',
        payload: value,
      });
    });
  });
}

const thirdAction = {
  type: 'THIRD_ACTION',
};

// immutable store state allowed by default, but not required
const initialState = fromJS({
  firstRun: false,
  secondRun: false,
  thirdRun: false,
});

function reducer(state, action) {
  switch(action.type) {

  case 'FIRST_ACTION':
    // Enter a sequence at FIRST_ACTION, SECOND_ACTION and THIRD_ACTION will be
    // dispatched in the order they are passed to batch
    return loop(
      state.set('firstRun', true),
      Effects.batch([
        Effects.promise(doSecondAction, 'hello'),
        Effects.constant(thirdAction)
      ])
    );

  case 'SECOND_ACTION':
    return state.set('secondRun', action.payload);

  case 'THIRD_ACTION':
    return state.set('thirdRun', true);

  default:
    return state;
  }
}

const store = install()(createStore)(reducer, initialState);

store
  .dispatch(firstAction);
  .then(() => {
    // dispatch returns a promise for when the current sequence is complete
    // { firstRun: true, secondRun: 'hello', thirdRun: true }
    console.log(store.getState().toJS());
  });
```

## Tutorial

### Install the store enhancer

```javascript
import { createStore } from 'redux';
import reducer from './reducers';
import { install } from 'redux-loop';

const store = install()(createStore)(reducer);
```

Installing `redux-loop` is as easy as installing any other store enhancer. You
can apply it directly over `createStore` or compose it with other enhancers
and middlewares. For best results, we recommend installing this enhancer such
that other enhancers like `devtools` will receive the result of `getState()`
from `redux-loop`.

### Write a reducer with some effects

```javascript
import { Effects } from 'redux-loop';
import { loadingStart, loadingSuccess, loadingFailure } from './actions';

export function fetchDetails(id) {
  return fetch(`/api/details/${id}`)
    .then((r) => r.json())
    .then(loadingSuccess)
    .catch(loadingFailure);
}

export default function reducer(state, action) {
  switch (action.type) {
    case 'LOADING_START':
      return loop(
        { ...state, loading: true },
        Effects.promise(fetchDetails, action.payload.id)
      );

    case 'LOADING_SUCCESS':
      return {
        ...state,
        loading: false,
        details: action.payload
      };

    case 'LOADING_FAILURE':
      return {
        ...state,
        loading: false,
        error: action.payload.message
      };

    default:
      return state;
  }
}
```

Any reducer case can return a `loop` instead of a state object. A `loop` joins
an updated model state with an effect for the store to process. There are
several options for effects, all available under the `Effects` object:

- `promise(factory, ...args)`
  - Accepts a `factory` function that returns a `Promise` for an action
    instance when called with `args`.
- `constant(action)`
  - Accepts an `action` instance to dispatch immediately once the current
    dispatch cycle is completed.
- `batch(effects)`
  - Accepts an array of other effects and runs them in parallel, dispatching
    the resulting actions once all effects are resolved.
- `none()`
  - A no-op action, for convenience when writing custom effect creators

### Easily test reducer results

```javascript
import test from 'tape';
import reducer, { fetchDetails } from './reducer';
import { loadingStart } from './actions';
import { Effects, loop } from 'redux-loop';

test('reducer works as expected', (t) => {
  const state = { loading: false };

  const result = reducer(state, loadingStart(1));

  t.deepEqual(result, loop(
    { loading: true },
    Effects.promise(fetchDetails, 1)
  ));
});
```

Effects are declarative specifications of the next behavior of the store. They
are only processed by an active store, pushing effecting behavior to the edge of
the application. You can call a reducer as many times with a given action and
state and always get a result which is `deepEqual`.

> CAVEAT
> For testing sanity, always pass a referenceable function to `Effects.promise`.
> Functions curried or bound from the same function with the same arguments are
> not equal within JavaScript, and so are best to avoid if you want to compare
> effects in your tests.

### Use the custom `combineReducers` if you need it

```javascript
import { createStore } from 'redux';
import { combineReducers, install } from 'redux-loop';

import { firstReducer, secondReducer } from './reducers';

const reducer = combineReducers({
  first: firstReducer,
  second: secondReducer,
{'fraction_non_alphanumeric': 0.11304012345679013, 'fraction_numerical': 0.00038580246913580245, 'mean_word_length': 3.614597240765465, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 25, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2509651', 'n_tokens_mistral': 3049, 'n_tokens_neox': 2948, 'n_words': 1083}