0

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

Ben Smith
  • 19,589
  • 6
  • 65
  • 93
Adee
  • 357
  • 1
  • 3
  • 13

1 Answers1

0

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

123 456 789 0
  • 10,565
  • 4
  • 43
  • 72
  • 1. `() => reset()` and `reset` in this case it works the same 2. The question is, why can't I return the entire `state` as in this example? https://github.com/ctrlplusb/easy-peasy/issues/146 – Adee Nov 01 '19 at 08:05
  • @Adee No it doesn't reset is not the same if you don't invoke the function. You are binding the click event function to b passed to the reset which can be different. You have to be careful with that. The reason why it's not working is because if you look at the type. There is a bug in the library, even if you follow their docs and their working sample it won't work if you try to return with spread operators. It only works if it's mutating the state directly. They also prefer mutating the state as this is your "reducer" part inside the actions function. – 123 456 789 0 Nov 01 '19 at 17:59
  • 1
    @Adee I don't know what magic they're doing in their library but if you print the console log for the state parameter it's undefined, but if you JSON.stringify(state) it's apparently there. – 123 456 789 0 Nov 01 '19 at 18:00