31

I was working on react project. I was trying to reload a component when we click the reload button. I implemented the onClick function as given below. But it is reloading the whole window. I just want to reload only that class component, not the whole window. Can anyone help me to solve this?

refreshPage() {
    window.location.reload();
  }
Gauranga
  • 379
  • 1
  • 5
  • 11

9 Answers9

28

The easiest way I have found out is to set a seed state, and use that in the key attribute of the rendered component. Whenever the seed changes now the component will be reloaded.

       const [seed, setSeed] = useState(1);
       const reset = () => {
            setSeed(Math.random());
        }
       <Component key={seed}/>
       <Button onClick={reset}>Reset</Button>

Whenever the Reload button is pressed now the component I need will be rerendered.

errorParser
  • 471
  • 5
  • 5
26

If you just want to reload the component's data, use the useEffect Hook:

useEffect(() => {
    fetchData();
}, [data]);
// fetchData() is called whenever data is updated.
tronman
  • 9,862
  • 10
  • 46
  • 61
Ren
  • 376
  • 4
  • 4
7

You can trigger a reload of components by updating the state.

class YourComponent extends Component {
  state = {
    reload: false
  };

  refreshPage = () => {
    this.setState(
      {reload: true},
      () => this.setState({reload: false})
    )
  }
}

This is dirty, but it may work. I have not tested it, though.

lukeocodes
  • 1,192
  • 1
  • 16
  • 31
1

You can create a new function. And you can call it on componentDidMount and refreshPage.

exampleFunction = () => {
   /** Do your job here */
}

componentDidMount(){
   /** your code */
   this.exampleFunction ();
   /** your code */
}

refreshPage(){
   this.exampleFunction ();
}
Alok Mali
  • 2,821
  • 2
  • 16
  • 32
1
refreshPage() {
  window.location.reload(false);
}

Reference at here: https://upmostly.com/tutorials/how-to-refresh-a-page-or-component-in-react

  • This will still reload the entire page, which is not what was asked for, and adding a `false` is a behavior that only has any meaning on Firefox https://developer.mozilla.org/en-US/docs/Web/API/Location/reload and not the desired behavior – Jorge Kunrath Dec 23 '22 at 20:49
0

If you want render your component then you can update any state using this.setState({}) in your function.

Bhawana
  • 372
  • 1
  • 6
0

window.location.reload(); will reload the current document, it like the Refresh button in browser, and it will not make any partial re rendering like AJAX. To achieve this by make setState in react.

Below the working sample :

import React from "react";

class RefreshComponent extends React.Component {
 constructor(props) {
   super(props);
   this.state = { name: "React Component reload sample" };
}
 submit() {
   this.setState({ name: "React Component Updated - " + new Date() });
}
render() {
  return (
    <div>
      {this.state.name}
      <br />
      <button
       onClick={() => {
         this.submit();
       }}
     >
       Submit
     </button>
    </div>
  );
 }
}

export default RefreshComponent;
Santhosh
  • 7
  • 2
0

The most maintainable way is to reactor existing components to handle "reload" in consistent way. ideally components should get data though props/context/redux instead of loading that on their own. This way you can refresh all with single call. Say it may be redux with some action like "REFRESH_HOTELS" or separate context with method reload.

as a last resort you may update key prop(to any other value, maybe just random string) and whole branch will be recreated including call to componentDidMount. it's know as "reset state by key prop" technique. but it's neither performance-safe nor really flexible way. better to avoid that until you really don't care of maintainability(or use as temporary solution... but typically "temporary solutions" stays as long as app exists)

skyboyer
  • 22,209
  • 7
  • 57
  • 64
0

You can check out this other thread: Can you force a React component to rerender without calling setState?

This is the top answer:

In class components, you can call this.forceUpdate() to force a rerender.

Documentation: https://facebook.github.io/react/docs/component-api.html

In function components, there's no equivalent of forceUpdate, but you can contrive a way to force updates with the useState hook.

Brandon
  • 469
  • 4
  • 10