CharlesStover / reactn

React, but with built-in global state management.
https://www.npmjs.com/package/reactn
MIT License
1.89k stars 85 forks source link

resetGlobal not working inside MDX #136

Closed bravo-kernel closed 4 years ago

bravo-kernel commented 4 years ago

Love this, so easy ❤️

I'm creating a simple reactn counter component for use inside a Gatsby MDX page. Everything works great except for resetGlobal(). Pressing the Reset button breaks the page but without console warnings or any other feedback so all pointers welcome. Am I missing something obvious here or chasing something that is not possible?

import React, { setGlobal, useGlobal, useDispatch, resetGlobal } from "reactn" // <-- reactn

setGlobal({
  count: 0,
})

const incrementReducer = (global, dispatch, action) => ({
  count: global.count + action.amount,
})

export default () => {
  const [ count ] = useGlobal('count');
  const increment = useDispatch(incrementReducer)

  return (
    <div>
      <button onClick={() => increment({ amount: 1 })}>Increment</button>
      <button onClick={() => resetGlobal() }>Reset</button>
      <pre>{count}</pre>
    </div>
  )
}
bravo-kernel commented 4 years ago

image

quisido commented 4 years ago

I believe the issue here is that calling resetGlobal also resets all subscriptions to the global state. This is an interesting use case. I believe until this point, reset has been used as a building block for utilities, not in the view itself. For example, running reset in between Jest tests can make sure that your unit tests do not cause side effects in other tests, or running reset after a server-side render can make sure that one user's data does not leak into the next user's application.

In this case, the reset button might should manually set the value to 0 instead of calling reset.

export default () => {
  const [count, setCount] = useGlobal("count")
  const increment = useDispatch(incrementReducer)

  return (
    <div>
      <button onClick={() => increment({ amount: 1 })}>Increment</button>
      <button onClick={() => setCount(0)}>Reset</button>
      <pre>{count}</pre>
    </div>
  )
}
bravo-kernel commented 4 years ago

Thanks for taking the time to reply, I was already (re)setting state to 0 but after seeing resetGlobal I could not resist trying that, would have been amazing 😉. Anyway, at least I now know it was not intended for this use case 💯

bravo-kernel commented 4 years ago

For those curious... this proof of concept utilizes reactn inside MDX to achieve high slider speeds. https://alt3.nl/tools/uuid-generator