kitbagjs / router

A type safe router for vuejs
https://router.kitbag.dev
MIT License
173 stars 4 forks source link

Route state #238

Closed stackoverfloweth closed 1 month ago

stackoverfloweth commented 2 months ago

This PR establishes the ability to fully utilize history state.

Now routes can define the expected format for state with the state option, using the same format we already use for route params. This includes the default types like String, Number, Boolean, etc. As well as support for defaults and custom params.

const route = createRoute({
  name: 'foo',
  state: {
    bar: Number
  }
})

State is set with router.push and router.replace within the options argument.

router.replace('foo', {}, { state: { bar: 14 } })

State is access from a resolved route with the state prop.

const route = useRoute()

route.state.foo // <-- 14

Open Questions

netlify[bot] commented 2 months ago

Deploy Preview for kitbag-router ready!

Name Link
Latest commit e724b5d3d0831f56dbe8f1d1e1be42d28aa0b68b
Latest deploy log https://app.netlify.com/sites/kitbag-router/deploys/66b8c9cf22e08c000851cc9f
Deploy Preview https://deploy-preview-238--kitbag-router.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

pleek91 commented 2 months ago

@stackoverfloweth let's discuss the possibility of merging state similar to route.params. But overall this is looking really good.

Also curious if you add a default to a state param will the types reflect that the value will always be defined? I saw the test to prove the value will be defined. But not the types. Might have missed that.

pleek91 commented 2 months ago

currently history.refresh does not do anything with state, which I assume will lose state if there was any. Is that expected?

This is a good question. I think we always want to update the state when

A fresh page load won't always have state but it might if the user refreshes the page via the browser.

should there be other ways of setting state?

I'd expect to be able to set state directly on the route and via route.update

route.state.foo = 'bar'

router.update({}, { state: { foo: 'bar' })

currently the params expect to be given a string but I'm not doing anything to explicitly turn values into a string when setting state. State comes in from history as unknown, should I expect that to be Record<string, string>?

We already discussed this but we need to use both the set and get from the param. Set when storing the value and get when retrieving it. That way we can use the user's defined logic. Otherwise we'll end up with weird things like losing class instances or not converting a csv like param back into an array.