esamattis / redux-hooks

βš“ React Hooks implementation for Redux
http://npm.im/@epeli/redux-hooks
MIT License
96 stars 4 forks source link

useMapState returns stale values when selecting data using useState values as dependecies #5

Closed mmazzarolo closed 5 years ago

mmazzarolo commented 5 years ago

Hi! Awesome library, thanks for sharing it. I noticed that using useMapState to selected data that has a useState dependency returns a stale value from the state.
Not sure if it's an issue of the library or if I'm making a mistake, but here is a CodeSandbox that demonstrates the issue:
https://codesandbox.io/s/0yz3m6v4r0

In the code I'm dispatching a Redux action (setReduxValues) after 5 seconds after mounting the component. The action adds some values in the Redux state and is dispatched and captured by the reducer successfully.
To get the updated value from the Redux state i use useMapState with a selector that has a dependency on some internal component state of the component... the issue is that if you change the internal component state before the setReduxValues action is dispatched, the selector will still use the old internal component state dependency instead of the updated one.
Since the doc says:

Without the dependencies array the state is mapped always when the component renders. When the store state updates the map state function is executed regardless of the deps array.

I would expect the selector to use the new updated dependency πŸ€” But maybe I'm missing something.

TLDR: In the CodeSandbox example, press the "Set letter to B" button asap and wait a few seconds.
You'll see that the printed value will be Redux value: IM THE VALUE OF A, but it should be Redux value: IM THE VALUE OF B
It will work correctly if instead of pressing the button asap you wait for at least 5 seconds.

Let me know if I can help in any other way!

esamattis commented 5 years ago

That indeed seems like a bug. useMapState is re-executed but it seems it does not update the map function reference properly.

It would be very helpful if you could create a failing test case for this.

I'm away from keyboard rest of the week so I'll look at this more closely later

esamattis commented 5 years ago

Merged the fix from https://github.com/epeli/redux-hooks/pull/6 and released in v0.5.3

mmazzarolo commented 5 years ago

@epeli and @jarvisaoieong thanks! Keep up with the good work on the lib, it's the best approach I've seen so far to handling redux state with hooks πŸ˜‰

esamattis commented 5 years ago

@mmazzarolo Thanks! I really appreciate the feedback!