diff --git a/src/__tests__/useQueryParam-SSR-test.tsx b/src/__tests__/useQueryParam-SSR-test.tsx new file mode 100644 index 0000000..26cf732 --- /dev/null +++ b/src/__tests__/useQueryParam-SSR-test.tsx @@ -0,0 +1,26 @@ +/** + * @jest-environment node + */ +import * as React from 'react'; +import { useQueryParam } from '../useQueryParam'; +import { renderToString } from 'react-dom/server'; +import QueryParamProvider from '../QueryParamProvider'; +import { makeMockLocation } from './helpers'; + +test('SSR initial query param', () => { + const Component = () => { + const [foo] = useQueryParam('foo'); + + return
{foo}
; + }; + + const location = makeMockLocation({ foo: 'bar' }); + + const result = renderToString( + + + + ); + + expect(result).toMatchInlineSnapshot(`"
bar
"`); +}); diff --git a/src/useQueryParam.ts b/src/useQueryParam.ts index 1aef5b7..faa17ed 100644 --- a/src/useQueryParam.ts +++ b/src/useQueryParam.ts @@ -58,7 +58,12 @@ export const useQueryParam = ( pathname = parseQueryString(location.search); } else { // not in browser - pathname = parseQueryURL(location.pathname).query; + let url = location.pathname; + if (location.search) { + url += location.search; + } + + pathname = parseQueryURL(url).query; } }