Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
How to set location query using react.router.dom v6?

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
  }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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() });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!