1

Problem: When I try to update url by adding query params, page reloads.

.tsx

useEffect(() => {
  requestResources()
  requestPosts({})
}, [])

const handleSlideItemClick = (value: string) => {
  history.push(`?resource=${value}`)
}

return (
  Box py={16} px='8px'>
    <SmoothSlider
      list={resources.list}
      name='resource'
      onSelect={handleSlideItemClick}
    />
  </Box>
)

Expectation: just update url by adding query params without page reload

I have also tried by <Link to={?resource=&{someValue}}>, result is same.

Madi Zhanabek
  • 67
  • 3
  • 8

3 Answers3

2

You can use pushState to achieve this functionality. It will not reload URL when you update the query URL.

You can implement like this:

var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?resource=newValue';

history.pushState({path:newurl},'',newurl);

Where newurl is your updated URL.

Source

Chetan Kumar
  • 427
  • 1
  • 3
  • 18
0

You should try to use <Link /> and set the property to as a function.

<Link to={location => ({ ...location, search: `?resource=${value}` })} />
Kirill Skomarovskiy
  • 1,535
  • 1
  • 7
  • 9
0

Try this code snippet. After the button press, the 'value' is maintained in React state and passed correctly to URL and React code is not reloaded.

import  React, {useState}  from 'react';

// https://stackoverflow.com/questions/61927235/why-history-pushquery-params-reloads-the-page-react
export default function App(props) {


    const [value, setValue] = useState(0)

    function handleSlideItemClick(target) {
        setValue( value + 1);
        // eslint-disable-next-line no-restricted-globals
        history.pushState ({ }, 'Page Title', `?resource=${value}`)
    }
    // I am using  button for simplicity 
    return <button type="button" onClick={handleSlideItemClick}>Click Me!</button>

}
Meera Datey
  • 1,913
  • 14
  • 15