atlassian-labs / react-resource-router

Configuration driven routing solution for React SPAs that manages route matching, data fetching and progressive rendering
https://atlassian-labs.github.io/react-resource-router
Apache License 2.0
202 stars 28 forks source link

Cannot change resourceContext between stories #76

Open theKashey opened 3 years ago

theKashey commented 3 years ago

Discovered in Storybook environment, when was not able to reset resourceContext between different stories.

Expectation: mounting/unmounting Router and especially MemoryRouter are not by previously used components.

albertogasparin commented 3 years ago

Yeah, currently only UniversalRouter sets up a ResourceContainer that can be set to local so works with storybooks and tests. Should be addressed by the cleanup of the multiple routers we export, where Router can just handle this stuff properly

theKashey commented 3 years ago

In my case, I was able to resolve the current situation by mocking useResource and calling .getData on the given object directly, which sound like a correct solution for storybooks, where "page" and the corresponding "route" does not exist and resource in normal terms should not be fetched.

theKashey commented 2 years ago

Still waiting for #145 as UniversalRouter is not exported.

tpuric commented 1 year ago

Hi @theKashey , I managed to create a workaround for this without needing to override any imports.

You can create a decorator utilising key (for router uniqueness to ensure unmounts are handled appropriately) and forcefully destroy any existing stores when mounting another Router.

export const withRouterDecoratorFn = ({ resources }: RouterDecoratorProps = {}): DecoratorFn =>
  function RouterDecorator(Story) {
    defaultRegistry.stores.clear(); // destroys existing react-sweet-state stores

    return (
      <Router
        key={key} // key for uniqueness
        routes={routes}
        history={history}
        resourceContext={routerContext} // context will be fresh for every mount (instantiating a new store)
      >
        <Story />
      </Router>
    );
  };

Codesandbox demo: https://codesandbox.io/s/react-resource-router-basic-routing-example-forked-qt67q6

theKashey commented 1 year ago

Please remove defaultRegistry.stores.clear(); there is a better place to put such destructive side effect into

As for the Router - this is the current recommendation.