riot / route

Simple isomorphic router
MIT License
212 stars 40 forks source link

Changing URL programmatically #174

Closed marcocelesti closed 7 months ago

marcocelesti commented 7 months ago

In a typical context of a CRUD, I would like, after a submit success of a form, to change the URL and navigate to page list. Example:

<edit-attrezzo> ... <form onsubmit={ submit }> ... <button type='submit'>Save</button> </form>

<script>

export default {

...

async submit(e) { e.preventDefault() const data = ... await StoreService.saveAttrezzo(data) route('/attrezzi') }

...

} </script> </edit-attrezzo>

This does not work for me. In Riot v3, I got it in that way. Is it possible to navigate to an URL programmatically? I can't get it. Thanks in advance

GianlucaGuarini commented 7 months ago

The Riot.js router is built on the top of the browser standards. You should be able to change your routes simply by calling thehistory.pushState method (in your case history.pushState({},'','/attrezzi'))

marcocelesti commented 7 months ago

Hi, thanks for your help. I modified as you suggested: <edit-attrezzo> ... html ... <script> export default { ... async submit(e) { e.preventDefault() await StoreService.saveAttrezzo(this.state.item_id, this.state.descrizione, this.state.icona) history.pushState({},'','/attrezzo') } } </script> <\edit-attrezzo>

In dashboard.riot (that is the container for main content) I have:

<route path="/attrezzo"> <anagrafica-attrezzi></anagrafica-attrezzi> </route> <route path="/attrezzo/create"> <edit-attrezzi item=""></edit-attrezzi> </route> <route path="/attrezzo/edit/:item"> <edit-attrezzi item="{ route.params.item }"></edit-attrezzi> </route>

When I submit the form, the url in browser actually changes to /attrezzo, but the route is not activated and nothing happens to main content. I can't understand the reason, since navigation by clicking on anchor tags works. Thanks in advance

GianlucaGuarini commented 7 months ago

I am sorry you need to push the path to the router as well since the popstate event is not automatically triggered. This code should do the trick

import { router } from '@riotjs/route'

const navigateTo = (path) => {
  // update the browser url
  history.pushState({}, '', path))
  // notify the path change to the riot router
  router.push(path)
}

Note that this code is code is only needed for the html5 history navigation In future releases the above code will be no longer needed since we will rely on https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation/onHistoryStateUpdated to detect the navigation transitions

marcocelesti commented 7 months ago

thank you, now it works!