Hotwire Discussion

How to change current url?

I want to implement a feature. When I enter content in the form of /posts/new, send a request to create a new record through JavaScript fetch, and then change the current url to /posts/:id/edit.

hey.com has similar features, but I found that they haven’t changed the current url.

Using the native history.replaceState will break the history of turbo. I found that there is a method Turbo.navigator.history.replace(location, restorationIdentifier), but the required Location class has no export.

So how to change the url and be compatible with Turbo history, any other suggestions?

2 Likes

Found a solution, use:

Turbo.navigator.history.replace({ absoluteURL: '/posts/1/edit' })
4 Likes

Word of warning for anyone checking this out on 7.0.0rc1 - I’m getting the following traceback when clicking a link after doing this:

Uncaught TypeError: url.href is undefined
    getAnchor turbo.es2017-esm.js:261
    getRequestURL turbo.es2017-esm.js:280
    locationWithActionIsSamePage turbo.es2017-esm.js:3450
    Visit turbo.es2017-esm.js:2229
    startVisit turbo.es2017-esm.js:3289
    visitProposedToLocation turbo.es2017-esm.js:2788
    visitProposedToLocation turbo.es2017-esm.js:4372
    proposeVisit turbo.es2017-esm.js:3281
    visit turbo.es2017-esm.js:4274
    followedLinkToLocation turbo.es2017-esm.js:4339
    clickBubbled turbo.es2017-esm.js:3217
    clickCaptured turbo.es2017-esm.js:3204
    start turbo.es2017-esm.js:3230
    start turbo.es2017-esm.js:4235
    start turbo.es2017-esm.js:5435

I’ve made an issue against Turbo to track it.