ctrlplusb / easy-peasy

Vegetarian friendly state for React
https://easy-peasy.dev
MIT License
5.03k stars 190 forks source link

undefined store on "contextmenu" event #784

Closed no-stack-dub-sack closed 2 years ago

no-stack-dub-sack commented 2 years ago

This may be a bit specific to a certain use-case / library, but figured I'd report it anyway. If you check out this codesandbox and right click anywhere in the "Euros" column header or context menu, easy-peasy throws an error due to the store being undefined.

image

The error comes from the <Foo /> component which consumes store state via the useStoreState hook. I can easily work around this by just passing in the state I need, but found this interesting.

The context menu is rendered inside a portal, and I thought maybe this has something to do with it, but its odd that its only on the "contextmenu" event that this seems to happen. Otherwise, the component is working fine and is clearly subscribed to the store.

Any ideas?

Thanks!

jmyrland commented 2 years ago

Inspecting the code using React Dev Tools, it seems that the context is "lost" because the ContextMenu is rendered as a sibling of App: image

The ContextMenu does not contain any StoreProvider, which in turn makes the useStoreState hook throw an error.

I was able to make it work by re-wrapping <Foo /> with a new provider, but with the same store:

                menuRenderer={() => {
                  return (
+                   <StoreProvider store={store}>
                      <Foo />
+                   </StoreProvider>
                  );
                }}

chrome_0HZafwmD6A

Hope that helps 👍

no-stack-dub-sack commented 2 years ago

Ah, so when its rendered via a left-click it's still within App's tree, but when you right-click it sits alongside App which explains why store seemed to only be undefined on right-click. This helps, thanks @jmyrland.