Easy-peasy - unable to return new state

867 Views Asked by At

Why can't I return the new state in this way (reset action)?

export interface TodosModel {
  items: string[];
  reset: Action<TodosModel>;
}

const todos: TodosModel = {
  items: [],

  // This action does not update the state
  reset: action(() => {
    return {
      items: []
    };
  })
};

I'm trying to achieve what is described here: https://github.com/ctrlplusb/easy-peasy/issues/146

Working example: https://codesandbox.io/s/easy-peasy-typescript-v3-vzc11

1

There are 1 best solutions below

3
On

There are two problems why it's not working.

You are not correctly binding the click action to reset

<button onClick={() => reset()}>Reset</button>

The callback passes in the state where you modify the state and lifecycle updates the state inside the action.

reset: action(state => {
    state.items = [];
  })

Here's a working copy. https://codesandbox.io/s/easy-peasy-typescript-v3-4j9c6