Skip to content

Commit

Permalink
fix: Hash preservation (#451)
Browse files Browse the repository at this point in the history
* fix: Remove hash from base before rendering URL

* test: Add e2e test for hash preservation
  • Loading branch information
franky47 authored Jan 9, 2024
1 parent e158622 commit 2f848dc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
34 changes: 34 additions & 0 deletions packages/e2e/cypress/e2e/hash-preservation.cy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/// <reference types="cypress" />

function runTest() {
cy.contains('#hydration-marker', 'hydrated').should('be.hidden')
cy.get('#string_set_a').click()
cy.location('search').should('eq', '?string=a')
cy.location('hash').should('eq', '#hash')
cy.get('#string_clear').click()
cy.location('hash').should('eq', '#hash')
}

describe('hash preservation (app router)', () => {
it('works in standard routes', () => {
cy.visit('/app/useQueryState#hash')
runTest()
})

it('works in dynamic routes', () => {
cy.visit('/app/useQueryState/dynamic/route#hash')
runTest()
})
})

describe('hash preservation (pages router)', () => {
it('works in standard routes', () => {
cy.visit('/pages/useQueryState#hash')
runTest()
})

it('works in dynamic routes', () => {
cy.visit('/pages/useQueryState/dynamic/route#hash')
runTest()
})
})
5 changes: 3 additions & 2 deletions packages/nuqs/src/update-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ function flushUpdateQueue(router: Router): [URLSearchParams, null | unknown] {
})
} else {
// App router
const url = renderURL(location.href.split('?')[0] ?? '', search)
const url = renderURL(location.origin + location.pathname, search)
debug('[nuqs queue (app)] Updating url: %s', url)
// First, update the URL locally without triggering a network request,
// this allows keeping a reactive URL if the network is slow.
Expand Down Expand Up @@ -214,9 +214,10 @@ function flushUpdateQueue(router: Router): [URLSearchParams, null | unknown] {
}

function renderURL(base: string, search: URLSearchParams) {
const hashlessBase = base.split('#')[0] ?? ''
const query = renderQueryString(search)
const hash = location.hash
return base + query + hash
return hashlessBase + query + hash
}

export function compose(
Expand Down

0 comments on commit 2f848dc

Please sign in to comment.