ionic-team / stencil-router-v2

Other
44 stars 13 forks source link

docs: navigating programmatically #18

Open sajTempler opened 3 years ago

sajTempler commented 3 years ago

I had a use case from router v1 like this: https://github.com/ionic-team/stencil-router/wiki/Navigating-Programmatically

and in v2 I didn't see any recommendation so here is what I can up with:

using stencil store I have a router initialized there as readonly property:

// store.ts

import { createStore } from "@stencil/store";

type Store = {
    readonly router: Router
}

const { state } = createStore<Store>({
    router: createRouter()
});

export { state };

for app-root definitions:

// app-root component
import { href, Route } from 'stencil-router-v2';
import { state } from '../../store/store';
const Router = state.router;

@Component({
  tag: 'app-root',
  styleUrl: 'app-root.css',
  shadow: true,
})
export class AppRoot {
  render() {
    return (
      <Host>
          <Router.Switch>

            <Route path="/" to="/week-view"/>

            <Route path="/week-view">
              <week-view></week-view>
            </Route>

            <Route path="/other-path">
              <other-path></other-path>
            </Route>

          </Router.Switch>
      </Host>
    );
  }
}

and finally in other components I can call navigation from JS like:

// anywhere
state.router.push(`/other-path`);

Is there better approach ? Cheers ;)

blahah commented 3 years ago

You only need to create a router in the shared file, you don't need to wrap it in a store. The router already loads its state from a store so it's a global instance and you can push to the router you import in any component.