# About

[![NPM version (>=0.4)](https://img.shields.io/npm/v/redux-undo.svg?style=flat-square)](https://www.npmjs.com/package/redux-undo) [![NPM Downloads](https://img.shields.io/npm/dm/redux-undo.svg?style=flat-square)](https://www.npmjs.com/package/redux-undo) [![Coverage Status](https://img.shields.io/coveralls/omnidan/redux-undo.svg?style=flat-square)](https://coveralls.io/r/omnidan/redux-undo) [![Dependencies](https://img.shields.io/david/omnidan/redux-undo.svg?style=flat-square)](https://david-dm.org/omnidan/redux-undo) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://raw.githubusercontent.com/omnidan/redux-undo/master/LICENSE.md)

*simple undo/redo functionality for redux state containers*

[![https://i.imgur.com/M2KR4uo.gif](https://i.imgur.com/M2KR4uo.gif)](https://github.com/omnidan/redux-undo-boilerplate)

**Protip:** Check out the [todos-with-undo example](https://github.com/omnidan/redux-undo/tree/master/examples/todos-with-undo) or the [redux-undo-boilerplate](https://github.com/omnidan/redux-undo-boilerplate) to quickly get started with `redux-undo`.

**Switching from 0.x to 1.0:** Make sure to update your programs to the [latest History API](/#history-api).

**Help wanted:** We are looking for volunteers to maintain this project, if you are interested, feel free to contact me at <me@omnidan.net>

**This README is about the new 1.0 branch of redux-undo, if you are using or plan on using 0.6, check out** [**the `0.6` branch**](https://github.com/omnidan/redux-undo/tree/0.6)

## Note on Imports

If you use Redux Undo in CommonJS environment, **don’t forget to add `.default` to your import**.

```diff
- var ReduxUndo = require('redux-undo')
+ var ReduxUndo = require('redux-undo').default
```

If your environment support es modules just go by:

```javascript
import ReduxUndo from 'redux-undo';
```

We are also supporting UMD build:

```javascript
var ReduxUndo = window.ReduxUndo.default;
```

**once again `.default` is required.**

## Installation

```
npm install --save redux-undo@beta
```

## API

```javascript
import undoable from 'redux-undo';
undoable(reducer)
undoable(reducer, config)
```

## Making your reducers undoable

`redux-undo` is a reducer enhancer (higher-order reducer). It provides the `undoable` function, which takes an existing reducer and a configuration object and enhances your existing reducer with undo functionality.

**Note:** If you were accessing `state.counter` before, you have to access `state.counter.present` after wrapping your reducer with `undoable`.

To install, firstly import `redux-undo`:

```javascript
// Redux utility functions
import { combineReducers } from 'redux';
// redux-undo higher-order reducer
import undoable from 'redux-undo';
```

Then, add `undoable` to your reducer(s) like this:

```javascript
combineReducers({
  counter: undoable(counter)
})
```

A [configuration](/#configuration) can be passed like this:

```javascript
combineReducers({
  counter: undoable(counter, {
    limit: 10 // set a limit for the size of the history
  })
})
```

## Apply redux-undo magic to specific slice of your state.

When you expose an undo redo history action to your app users, you will not want those action to apply on your whole redux state. Lets see this with naive document editor state.

```javascript
const rootReducer = combineReducers({
  ui: uiReducer,
  document: documentReducer,
})
```

wrapping the documentReducer with undoable higher order reducer

```javascript
const rootReducer = combineReducers({
  ui: uiReducer,
  document: undoable(documentReducer),
})
```

will provide only the document mountpoint of your state with an history.

an even more advanced usage would be to have many different mountpoint of your redux state, managed under redux-undo.

```javascript
const rootReducer = combineReducers({
  ui: uiReducer,
  document: undoable(documentReducer, {
    undoType: 'DOCUMENT_UNDO',
    redoType: 'DOCUMENT_REDO',
    // here you will want to configure specific redux-undo action type  
  }),
  anotherDocument: undoable(documentReducer, {
    undoType: 'ANOTHERDOCUMENT_UNDO',
    redoType: 'ANOTHERDOCUMENT_REDO',
    // here you will want to configure specific redux-undo action type  
  }),
})
```

Don't forget to configure specific redux-undo action type for each of your mount point if you don't want to see your different history to undo/redo in sync.

## History API

Wrapping your reducer with `undoable` makes the state look like this:

```javascript
{
  past: [...pastStatesHere...],
  present: {...currentStateHere...},
  future: [...futureStatesHere...]
}
```

Now you can get your current state like this: `state.present`

And you can access all past states (e.g. to show a history) like this: `state.past`

**Note:** Your reducer still receives the current state, a.k.a. `state.present`. Therefore, you would not have to update an existing reducer to add undo functionality.

## Undo/Redo Actions

Firstly, import the undo/redo action creators:

```javascript
import { ActionCreators } from 'redux-undo';
```

Then, you can use `store.dispatch()` and the undo/redo action creators to perform undo/redo operations on your state:

```javascript
store.dispatch(ActionCreators.undo()) // undo the last action
store.dispatch(ActionCreators.redo()) // redo the last action

store.dispatch(ActionCreators.jump(-2)) // undo 2 steps
store.dispatch(ActionCreators.jump(5)) // redo 5 steps

store.dispatch(ActionCreators.jumpToPast(index)) // jump to requested index in the past[] array
store.dispatch(ActionCreators.jumpToFuture(index)) // jump to requested index in the future[] array

store.dispatch(ActionCreators.clearHistory()) // Remove all items from past[] and future[] arrays
```

## Configuration

A configuration object can be passed to `undoable()` like this (values shown are default values):

```javascript
undoable(reducer, {
  limit: false, // set to a number to turn on a limit for the history

  filter: () => true, // see `Filtering Actions`
  groupBy: () => null, // see `Grouping Actions`

  undoType: ActionTypes.UNDO, // define a custom action type for this undo action
  redoType: ActionTypes.REDO, // define a custom action type for this redo action

  jumpType: ActionTypes.JUMP, // define custom action type for this jump action

  jumpToPastType: ActionTypes.JUMP_TO_PAST, // define custom action type for this jumpToPast action
  jumpToFutureType: ActionTypes.JUMP_TO_FUTURE, // define custom action type for this jumpToFuture action

  clearHistoryType: ActionTypes.CLEAR_HISTORY, // define custom action type for this clearHistory action
  // you can also pass an array of strings to define several action types that would clear the history
  // beware: those actions will not be passed down to the wrapped reducers

  initTypes: ['@@redux-undo/INIT'], // history will be (re)set upon init action type
  // beware: those actions will not be passed down to the wrapped reducers

  debug: false, // set to `true` to turn on debugging
  ignoreInitialState: false, // prevent user from undoing to the beginning, ex: client-side hydration

  neverSkipReducer: false, // prevent undoable from skipping the reducer on undo/redo and clearHistoryType actions
  syncFilter: false // set to `true` to synchronize the `_latestUnfiltered` state with `present` when an excluded action is dispatched
})
```

**Note:** If you want to use just the `initTypes` functionality, but not import the whole redux-undo library, use [redux-recycle](https://github.com/omnidan/redux-recycle)!

### Initial State and History

You can use your redux store to set an initial history for your undoable reducers:

```javascript
import { createStore } from 'redux';

const initialHistory = {
  past: [0, 1, 2, 3],
  present: 4,
  future: [5, 6, 7]
}

// Alternatively use the helper:
// import { newHistory } from 'redux-undo';
// const initialHistory = newHistory([0, 1, 2, 3], 4, [5, 6, 7]);

const store = createStore(undoable(counter), initialHistory);
```

Or just set the current state like you're used to with Redux. Redux-undo will create the history for you:

```javascript
import { createStore } from 'redux';

const store = createStore(undoable(counter), {foo: 'bar'});

// will make the state look like this:
{
  past: [],
  present: {foo: 'bar'},
  future: []
}
```

### Grouping Actions

If you want to group your actions together into single undo/redo steps, you can add a `groupBy` function to `undoable`. `redux-undo` provides `groupByActionTypes` as a basic `groupBy` function:

```javascript
import undoable, { groupByActionTypes } from 'redux-undo';

undoable(reducer, { groupBy: groupByActionTypes(SOME_ACTION) })
// or with arrays
undoable(reducer, { groupBy: groupByActionTypes([SOME_ACTION]) })
```

In these cases, consecutive `SOME_ACTION` actions will be considered a single step in the undo/redo history.

#### Custom `groupBy` Function

If you want to implement custom grouping behaviour, pass in your own function with the signature `(action, currentState, previousHistory)`. If the return value is not `null`, then the new state will be grouped by that return value. If the next state is grouped into the same group as the previous state, then the two states will be grouped together in one step.

If the return value is `null`, then `redux-undo` will not group the next state with the previous state.

The `groupByActionTypes` function essentially returns the following:

* If a grouped action type (`SOME_ACTION`), the action type of the action (`SOME_ACTION`).
* If not a grouped action type (any other action type), `null`.

When `groupBy` groups a state change, the associated `group` will be saved alongside `past`, `present`, and `future` so that it may be referenced by the next state change.

After an undo/redo/jump occurs, the current group gets reset to `null` so that the undo/redo history is remembered.

### Filtering Actions

If you don't want to include every action in the undo/redo history, you can add a `filter` function to `undoable`. This is useful for, for example, excluding actions that were not triggered by the user.

`redux-undo` provides you with the `includeAction` and `excludeAction` helpers for basic filtering. They should be imported like this:

```javascript
import undoable, { includeAction, excludeAction } from 'redux-undo';
```

Now you can use the helper functions:

```javascript
undoable(reducer, { filter: includeAction(SOME_ACTION) })
undoable(reducer, { filter: excludeAction(SOME_ACTION) })

// they even support Arrays:

undoable(reducer, { filter: includeAction([SOME_ACTION, SOME_OTHER_ACTION]) })
undoable(reducer, { filter: excludeAction([SOME_ACTION, SOME_OTHER_ACTION]) })
```

**Note:** Since [`beta4`](https://github.com/omnidan/redux-undo/releases/tag/beta4), only actions resulting in a new state are recorded. This means the (now deprecated) `distinctState()` filter is auto-applied.

#### Custom Filters

If you want to create your own filter, pass in a function with the signature `(action, currentState, previousHistory)`. For example:

```javascript
undoable(reducer, {
  filter: function filterActions(action, currentState, previousHistory) {
    return action.type === SOME_ACTION; // only add to history if action is SOME_ACTION
  }
})

// The entire `history` state is available to your filter, so you can make
// decisions based on past or future states:

undoable(reducer, {
  filter: function filterState(action, currentState, previousHistory) {
    let { past, present, future } = previousHistory;
    return future.length === 0; // only add to history if future is empty
  }
})
```

#### Combining Filters

You can also use our helper to combine filters.

```javascript
import undoable, {combineFilters} from 'redux-undo'

function isActionSelfExcluded(action) {
  return action.wouldLikeToBeInHistory
}

function areWeRecording(action, state) {
  return state.recording
}

undoable(reducer, {
  filter: combineFilters(isActionSelfExcluded, areWeRecording)
})
```

### Ignoring Actions

When implementing a filter function, it only prevents the old state from being stored in the history. **`filter` does not prevent the present state from being updated.**

If you want to ignore an action completely, as in, not even update the present state, you can make use of [redux-ignore](https://github.com/omnidan/redux-ignore).

It can be used like this:

```javascript
import { ignoreActions } from 'redux-ignore'

ignoreActions(
  undoable(reducer),
  [IGNORED_ACTION, ANOTHER_IGNORED_ACTION]
)

// or define your own function:

ignoreActions(
  undoable(reducer),
  (action) => action.type === SOME_ACTION // only add to history if action is SOME_ACTION
)
```

## What is this magic? How does it work?

Have a read of the [Implementing Undo History recipe](https://redux.js.org/recipes/implementing-undo-history) in the Redux documents, which explains in detail how redux-undo works.

## Gitter Chat / Support

If you have a question or just want to discuss something with other redux-undo users/maintainers, [chat with the community on gitter.im/omnidan/redux-undo](https://gitter.im/omnidan/redux-undo)

Also, look at the documentation over at [redux-undo.js.org](https://redux-undo.js.org/).

## License

MIT, see `LICENSE.md` for more information.


# FAQ

## Table of Contents

* [Where can I get help using `redux-undo`?](/main/faq#where-can-i-get-help-using-redux-undo)
* [Where can I find examples of how to use `redux-undo`?](/main/faq#where-can-i-find-examples-of-how-to-use-redux-undo)
* [How do I prevent cluttering up history with rapidly changing state?](/main/faq#how-do-i-prevent-cluttering-up-history-with-rapidly-changing-state)
* [Can I have multiple, separate undoable functions?](/main/faq#can-i-have-multiple-separate-undoable-functions)
* [Why are my actions not being filtered?](/main/faq#why-are-my-actions-not-being-filtered)
* [What is `_latestUnfiltered`? Can I remove it?](/main/faq#what-is-_latestunfiltered-can-i-remove-it)
* [Why am I getting `Cannot find module 'redux-undo'`?](/main/faq#why-am-i-getting-cannot-find-module-redux-undo)
* [How do I set an initial state/history?](/main/upgrading-to-1.0#initialstate)
* [How do I upgrade from 0.X to 1.0?](/main/upgrading-to-1.0)
* [How can I Undo or Redo a batch of actions at the same time ?](/main/examples/undo-redo-batch-actions)

## Where can I get help using `redux-undo`?

To get an understanding of the basics, read through the [README](https://github.com/omnidan/redux-undo/tree/9a05150d6bcd3f71e56c3d9cb5e8669ac3d5c1dd/README.md) and checkout some [examples](/main/faq#where-can-i-find-examples-of-how-to-use-redux-undo).

To get help with a specific use case, see if there is already an example in these docs or the examples. If not, ask for help in the [gitter chat](https://gitter.im/omnidan/redux-undo)!

If it seems you have found a bug or you are itching for a new feature, go ahead and submit it as an issue following the template provided. Please reserve Github issues for bugs and features **only**. Ask any other questions on the gitter chat and someone will probably be able to help you with your problem.

[*back to top*](/main/faq#table-of-contents)

## Where can I find examples of how to use `redux-undo`?

Look at the `examples/` directory of the project folder. The `todos-with-undo/` is a good project to start messing with.

```bash
$ git clone https://github.com/omnidan/redux-undo.git
$ cd redux-undo/examples/todos-with-undo
$ npm install
$ npm start
```

Just open <http://localhost:3000> and you are good to go!

[*back to top*](/main/faq#table-of-contents)

## How do I prevent cluttering up history with rapidly changing state?

The `throttled-drag/` project found the `examples/` directory gives a good demonstration of how to debounce undos (the filter is in `util/undoFilter.js`).

This general question has different solutions depending on your exact problem. Let's say you have one or more rapidly dispatched actions, for example `MOVE_CURSOR` and `UPDATE_OBJECT_POS`, that ends with a lone action `PLACE_OBJECT`, and you only want to record the end state after `PLACE_OBJECT`. Then you can simply use a filter `excludeAction(['MOVE_CURSOR', 'UPDATE_OBJECT_POS'])`

For more complex requirements, consider writing your own [custom filter](https://github.com/omnidan/redux-undo#custom-filters).

[*back to top*](/main/faq#table-of-contents)

## Can I have multiple, separate undoable functions?

Yes you can! Simply wrap each reducer with its own `undoable()`.

```javascript
const rootReducer = combineReducers({
  someData: undoable(dataReducer),
  otherData: undoable(otherDataReducer)
});
```

Do not forget to setup different undo/redo types to undo/redo each slice separately.

```javascript
someData: undoable(dataReducer, {
  undoType: "DATA_UNDO",
  redoType: "DATA_REDO"
  // There is also jumpType, jumpToPastType, jumpToFutureType, clearHistoryType, and initTypes (which is an array of action types)
});
```

If you wish to have a single conglomerate history that a user can undo one action at a time, you can wrap the root reducer with `undoable()`.

```javascript
const rootReducer = undoable(
  combineReducers({
    someData: dataReducer,
    otherData: otherDataReducer
  }),
  {...options...}
);
```

You probably need to use [custom filters](https://github.com/omnidan/redux-undo#custom-filters) and/or [`groupBy`](https://github.com/omnidan/redux-undo#grouping-actions) to undo/redo in reasonable chunks.

[*back to top*](/main/faq#table-of-contents)

## Why are my actions not being filtered?

If you are trying to prevent actions from changing state, **that is not what `filter` is for**. The `filter` option only prevents state changes from becoming part of the history, i.e. the new state being pushed into `state.past`. If you need this functionality, check out [redux-ignore](https://github.com/omnidan/redux-ignore).

On the other hand, here is how to use the helper functions:

```javascript
undoable(myReducer, {
  filter: combineFilters(
    // includeAction/excludeAction helpers take an array of action type strings
    includeAction(["MY_ACTION", "ANOTHER_ACTION"]),
    customFilter
  )
});
```

When writing a custom filter, return `true` for actions that you want to keep in history.

```javascript
function onlyEveryThird(action, newState, history) {
  // Access the whole history object
  let { past, present, future, limit } = history;

  return newState.count % 3 === 0; // Only update history every third count
}
```

[*back to top*](/main/faq#table-of-contents)

## What is `_latestUnfiltered`? Can I remove it?

### What is it?

State wrapped by `undoable()` contains the field `_latestUnfiltered` alongside `past`, `present`, etc. This field is used to keep track of state that should be put in the history but cannot yet because the previous action(s) were filtered. It is basically a temporary variable between filtered actions.

```javascript
// This action is filtered, so present cannot be pushed into past right away
_latestUnfiltered = present;
present = newState;

// With the next unfiltered action...
past = [...past, _latestUnfiltered]; // Now we can add it
```

### Can I remove it?

Short answer, no. It is an integral part of filtering actions from history and cannot be removed from the library. You can ignore it completely, but overriding/removing it may have unwanted consequences.

While there is a tad more overhead handling actions in the reducer, it is necessary with the current setup. In the future, there might be optimization that makes this field less burdensome for users that do not use the filtering functionality.

[*back to top*](/main/faq#table-of-contents)

## Why am I getting `Cannot find module 'redux-undo'`?

If you are using redux-undo in a CommonJS or UMD environment, you need to add `.default` to your imports.

```javascript
// CJS
var undoable = require("redux-undo").default;

// UMD
var undoable = window.ReduxUndo.default;
```

ES6 imports should work without a hitch.

```javascript
import undoable from "redux-undo";
```

If this fixed your issue, you might also want to checkout how to [upgrade from 0.6 to 1.0](/main/upgrading-to-1.0).

[*back to top*](/main/faq#table-of-contents)


# Examples

* [Undoing/redoing actions in batches](/main/examples/undo-redo-batch-actions)
* [Converting a regular reducer to undoable reducer](/main/examples/converting-regular-reducer-to-undoable-one)


# Undoing/redoing batches of actions at a time

This is an example of how to use custom groupBy to undo-redo a batch of actions at the same time.

This method remains the ability to group by action types but also enables us to group a batch of actions.

* [x] Group by action types by default
* [x] Group batch actions on demand, with `start()` and `end()`

For example, an `onClick` event handler may dispatch a batch of actions. My way is to surround the batch of actions with `start()` and `end()`.

```javascript
import { batchGroupBy } from './batchGroupBy'

const mapDispatchToProps = (dispatch, ownProps) => ({
  onClick: (evt) => {
    batchGroupBy.start()

    dispatch(action1)
    dispatch(action2)
    dispatch(action3)

    batchGroupBy.end()
  }
});
```

The basic idea is that once `batch.start()`, all the subsequent actions will return the same group value until meet `batch.end()`. Then `redux-undo` will automatically save them in one group, without inserting a new state in the `past` array.

```javascript
// batchGroupBy.js

import { groupByActionTypes } from 'redux-undo'

export const batchGroupBy = {
  _group: null,
  start(group = cuid()) {
    this._group = group
  },
  end() {
    this._group = null
  },
  init(rawActions) {
    const defaultGroupBy = groupByActionTypes(rawActions)
    return (action) => this._group || defaultGroupBy(action)
  }
};
```

Note that we create a unique id whenever we call `batch.start()`. In such case, if two batches are called back-to-back, they have different group values so that they will be stored in two states, rather than one state.

Then we can config the reducer like below:

```javascript
import { batchGroupBy } from './batchGroupBy'

const rootReducer = combineReducers({
  ui: uiReducer,
  document: undoable(documentReducer, {
    groupBy: batchGroupBy.init([SOME_ACTION])
  }),
});
```

An array of action types can be passed into `init()`, which keeps the ability of grouping by action types if they are not within the scope of `start()` and `end()`.


# Converting a regular reducer to undoable reducer

This example shows how to convert a regular reducer to undoable reducer.

We will create an application that implements github labels(the ones we add to the github issues).

```javascript
// ./src/reducer.js

import undoable from 'redux-undo';

const initialState = {
    labels: []
};

function reducer(state = initialState, action) {
    switch(action.type) {
        case 'ADD_LABEL':
            return {
                ...state,
                labels: [...state.labels, {
                    id: action.id,
                    name: action.name,
                    color: action.color,
                    description: action.description
                }]
            }
        case 'DELETE_LABEL':
            return {
                ...state,
                labels: state.labels.filter(label => label.id !== action.id)
            }
        default:
            return state;
    }
}

// Calling an undoable with our regular reducer gives an undoable reducer
export default undoable(reducer);
```

```javascript
// ./src/actions.js
let labelId = 1;

export const addLabel = (name, color, description) => ({
    type: 'ADD_LABEL',
    id: labelId++,
    name,
    description,
    color
});

export const deleteLabel = id => ({
    type: 'DELETE_LABEL',
    id
});
```

./src/index.js

```javascript
import {createStore} from 'redux';
import reducer from './reducer';
import {addLabel, deleteLabel} from './actions';
import {ActionCreators} from 'redux-undo';

const store = createStore(reducer);

/**
 * Log the initial state.
 * Consoles the following:
 * {
 *  past: [],
 *  present: {
 *      labels: []
 *  },
 *  future: []
 * }
*/
console.log(store.getState());

// So to get the present state we access the present attribute of the state
console.log(store.getState().present);

// Everytime the state changes, Log it.
store.subscribe(() => console.log(store.getState().present));

// Add a new Label
store.dispatch(addLabel('bug', 'red', 'Something in this project needs to be fixed'));

// Add a new Label
store.dispatch(addLabel('docs', 'pink', 'Related to documentation'));

// Add a new Label
store.dispatch(addLabel('good first issue', 'pink', 'Great for aspiring open source contributors'));

// To undo an action
store.dispatch(ActionCreators.undo());

// To redo an action
store.dispatch(ActionCreators.redo());
```


# Upgrading to 1.0

## Imports

CommonJS and UMD bundles now need a `.default` added to your imports.

```javascript
// CJS
var undoable = require("redux-undo").default;

// UMD
var undoable = window.ReduxUndo.default;
```

ES6 imports should work as expected.

```javascript
import undoable from "redux-undo";
```

## `distinctState()` filter applied by default

In 1.0 and greater, state is only added to history if it is different than the previous state (checked by object reference equality `===`). The `distinctState()` filter is now deprecated and removed as there is no need for it.

## History API change in versions `< 0.4`

In versions 0.3 and earlier, the history state was stored in the form.

```javascript
{
  currentState: {...currentStateHere...},
  history: {
    past: [...pastStatesHere...],
    present: {...currentStateHere...},
    future: [...futureStatesHere...]
  }
}
```

In versions `0.4` and greater, the full history is exposed directly.

```javascript
{
  past: [...pastStatesHere...],
  present: {...currentStateHere...},
  future: [...futureStatesHere...]
}
```

## InitialState

Before `1.0`, you would pass an `initialState` or `initialHistory` as a config option.

```javascript
undoable(myReducer, {
  initialState: {
    myState: "initial",
    otherField: true
  }
  // or initialHistory with past, present, and future
});
```

Now, these options are removed in favor of Redux's `preloadedState` parameter.

```javascript
const rootReducer = combineReducers({
  root: undoable(myReducer)
});

const store = createStore(rootReducer, {
  root: {
    myState: "initial",
    otherField: true
  }
});
```

When providing initial state, redux-undo will automatically detect whether or not it is a complete history (with `past`, `present`, `future`) or not. If it is not, it will automatically convert it to one.

If you wish to provide an initial history, e.g. you want to prefill `past` to recover a previous session, you **must** provide all three fields for redux-undo to recognize it as a history object.

```javascript
const store = createStore(rootReducer, {
  root: {
    past: ["from", "previous", "session"],
    present: "now"
    // `future` not provided!! Redux-undo will not recognize this as a history
    // and will instead set present = {past: [...], present: 'now'}

    // To fix, pass `future: []`
  }
});
```

For information about `initialState` with typescript, [look here](/main/working-with-ts#typing-initial-state).

## 0.X behaviour for pushing filtered state into history, and the syncFilter option

When dealing with filtered state, the old behaviour was to keep track of the "trailing" state (state 4 in this example).

```
initial action: Initial state
included action: state 1 - add initial state to history
included action: state 2 - add state 1 to history
filtered action: state 3 - do nothing
filtered action: state 4 - do nothing
included action: state 5 - add state 4 to history
```

However, states 3 and 4 were the result of filtered actions and should probably not be added to history. Instead, state 2 should be the last state pushed into history. Using [`_latestUnfiltered`](/main/faq#what-is-_latestunfiltered-can-i-remove-it), this is now the default in 1.X

```
initial action: Initial state
included action: state 1 - add initial state to history
included action: state 2 - add state 1 to history
filtered action: state 3 - store state 2 in _latestUnfiltered
filtered action: state 4 - do nothing
included action: state 5 - add _latestUnfiltered (state 2) to history
```

If you still need to old behaviour, use the syncFilter option.

```javascript
undoable(myReducer, { syncFilter: true })
```


# Working with Typescript

## Importing redux-undo in typescript

By default, you must use the `import = require` syntax when using typescript. You can read more in their [documentation](https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require).

```typescript
import ReduxUndo = require('redux-undo')

const undoable = ReduxUndo.default
```

Alternatively, by changing your `tsconfig.json`, you can import using the ES style syntax. Both `esModuleInterop` and `allowSyntheticDefaultImports` need to be set to true.

```javascript
{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  }
}
```

```typescript
// myReducer.ts
import undoable, { ActionCreators } from 'redux-undo'
```

## Typing Initial State

While using typescript, you might run into issues when providing initial state for your undoable reducers. To get around this issue, you will need to cast types, a.k.a. blantly lie to the compiler.

When you are providing state as your reducer will receive them without a predefined history, you must type cast to `any` then `StateWithHistory`.

```typescript
import { StateWithHistory } from 'redux-undo'

createStore(rootReducer, {
  // Have to cast to any first
  undoableState: (initialState as any) as StateWithHistory<typeof initialState>
})
```

With a predefined history, you can lie "more directly."

```typescript
createStore(rootReducer, {
  undoableState: withHistory as StateWithHistory<typeof withHistory['present']>
})
```

Remember, you have to pass **all of and only** the fields `past`, `present`, and `future` in the history. Read more about [initialState with redux-undo](/main/upgrading-to-1.0#initialstate).


