Quentin
Quentin

Reputation: 371

What is the best way to refresh a page?

I would like to know what is the best way to refresh the page after typing.

For example, I press a button that modifies the name of a product, how can I do that from the moment I validate my modification, the changes appear immediately, without having to manually refresh the browser page.

I saw some example with react-router, doing a redirect or using 'history.push', I also saw with the 'window.location.reload (false)' but it doesn't feel right because you can 'see' that the page refresh (yes you don't manually refresh but ... maybe there is something better to do)

Upvotes: 0

Views: 150

Answers (3)

Anup
Anup

Reputation: 629

It all depends on your requirement actually.

If you want to reload the page to get something which can only be achieved by reloading then use

window.location.reload()

If you want to reload just to get the data then make the API call and connect your component with the state that gets the value after the API call

If you want to maintain the history stack the use

history.push()

If you dont want to maintain the history stack the use

history.replace()

Some fancy times when you want to set cookie or storage to your page but dont want to refresh current page you can use window.open with the origin and target

window.open(window.location.origin, '_blank')

Upvotes: 1

TeachMe
TeachMe

Reputation: 635

You can use useState hooks of react to view the changes without refreshing the window.

In every state change, which means the change of value on the given state, react automagically rerender to show the latest data.

const [productName, setProductName] = useState('');

cosnt handleButtonClick = (name) => setProductName(name)

return (
<>
 Production Name: {productName} // Product name changes on every button click. 
 <button onClick={() => handlebuttonClick(dynamicallySendRequiredDataFromHere)}> Change product name </button>
<>
)

Upvotes: 1

Ernesto Stifano
Ernesto Stifano

Reputation: 3130

Well, the best way is to not refresh the page at all.

Specially if you are using React. Every piece of data that you display on your UI is supposed to be stored in some kind of state. Even if that data should somehow be validated asynchronously (I think this is your case), once done, you should trigger a state change that will cause the interested components to re-render and display the new information.

Upvotes: 2

Related Questions