I am trying to set location.query using react.router.dom v6. As I set my query inside service I can not use hook so I use
const history = createBrowserHistory()
This code is setting query, but if I change the page it will disappear. It will work if after setting the query I will refresh the page. In this case, the query will work fine. I think this is the issue of using router v6, I created a custom router but it didn't help. Maybe exist somehow to fix this?
history.ts
import { createBrowserHistory } from 'history'
export const history = createBrowserHistory()
export const getQueryPathname = (): string => history.location.pathname
export const setUrlQuery = <T>(urlQueryName: string, urlQuery: T): void => {
const pathname = getQueryPathname()
history.push({
pathname: pathname,
search: `?${urlQueryName}=${String(urlQuery)}`,
})
}
Custom Router
import { History } from 'history'
import React, { useLayoutEffect, useState } from 'react'
import { Router, RouterProps } from 'react-router-dom'
interface CustomRouterProps {
history: History
props?: RouterProps
}
const CustomRouter: React.FC<CustomRouterProps> = ({ history, ...props }) => {
const [state, setState] = useState({
action: history.action,
location: history.location,
})
useLayoutEffect(() => history.listen(setState), [history])
return <Router {...props} location={state.location} navigationType={state.action} navigator={history} />
}
export default CustomRouter
service where I use setUrlQuery
testFunction(id: number): void {
setUrlQuery('query', id)
// some other logic
}
I am using useHistory() hook from react-router-dom and doing something like:
const history = useHistory();
const queryParams = new URLSearchParams(location.search);
queryParams.append('query', id)
history.replace({ search: queryParams.toString() });