Nicolas S.Xu
Nicolas S.Xu

Reputation: 14554

How to use react-router 4.0 to refresh current route? not reload the whole page

'react-router-dom' has refresh function here, but I don't know how to call this method, also their well formatted document doesn't bother to explain this.

window.location.reload() doesn't work for me, because it wipes out the app store as well. I changed some data, and then need to reload the route with updated data.

I also read this: https://github.com/ReactTraining/react-router/issues/1982 https://github.com/ReactTraining/react-router/issues/2243

this thread is exactly discussing my question: https://github.com/ReactTraining/react-router/issues/4056

and still clueless how to do it. This basic function should not require too much effort, but after spending huge amount of effort, I can't reload current route.

here is my code:

@inject('store') @observer
export default class PasswordInput extends Component {
    constructor (props) {
        super(props)
        this.setPwd = this.setPwd.bind(this)
        this.submit = this.submit.bind(this)
    }

    componentWillMount() {
        this.case = this.props.store.case

        this.setState({refresh: false})
    }
    setPwd(e) {
        // console.log(e)
        this.case.pwd = e.target.value

    }
    submit() {
        console.log(this.props.caseId)
        this.setState({refresh: true})

    }

    render() {
        return (
            <Container>
                <div>{this.state.refresh}</div>
                { (this.state.refresh) && <Redirect refresh={true} to={'/cases/' + this.props.caseId}></Redirect>}
                <br />
                <Grid columns="three">
                    <Grid.Row>
                        <Grid.Column key={2}>
                            <Form>
                                <label>Enter Password</label>
                                <input placeholder="empty"  type="text" onChange={this.setPwd} value={this.case.pwd}></input>                               

                                <Button name="Save" color="green" size="mini" 
                                style={{marginTop:'1em'}}
                                onClick={this.submit}>
                                    Submit
                                </Button>                               
                            </Form>
                        </Grid.Column>
                    </Grid.Row>
                </Grid>
            </Container>
        )
    }
}

Upvotes: 19

Views: 61478

Answers (11)

viktarpunko
viktarpunko

Reputation: 353

The solution that works for me. https://github.com/remix-run/react-router/issues/1982#issuecomment-305735126

 history.push(redirectUrl);
 history.go(0);

Upvotes: 0

Yunay Hamza
Yunay Hamza

Reputation: 11

I am using redirct at the beginning, which removes trailing slash from the end of the url

 <Redirect key={0} from="/:url*(/+)" to={pathname.slice(0, -1)} />

Then you can set your route path with trailing slash on the end and it will be reloaded every time.

Upvotes: 0

akosidoctor26
akosidoctor26

Reputation: 95

I used key and state to solve this in our app.

In my case, we want to refresh without fully reloading when clicking the same menu even though it is active already.

So, in our menu click, I have this code. It doesn't have to be uuid, it can be anything as long as it changes every time you trigger. It doesn't have to be an object with reloadKey prop too, it's up to you. It can be as simple as string only, I just coded it this way.

push({state: {reloadKey: uuid()}}); 

Then, I set the key in the Route.

PrivateRoute is my wrapper that wraps Route from react-router-dom.

const {state: { reloadKey } = {}}  =  location;
<PrivateRoute key={reloadKey} path="/path" component={Component} />

Because the key changed, this will trigger the component to re-mount and will not trigger a full page reload.

Upvotes: 1

Leo Santos
Leo Santos

Reputation: 300

All right, I have tried pretty much every answer before but nothing worked. This was the only way I could force a reload

I'm using redux but you could also use any state management you prefer

1 - Set a boolean to false

2 - Add an onClick function to your Link/button that will set the boolean true

3 - Add that boolean variable to useEffect()

This will trigger the re-render

useEffect(() => {
   // Do stuff...
},[forceReload])

const forceReload = () => {
   dispatch({ type: RELOAD });
   // OR useState or whatever you want
   setForceReload(true);
}


...
<Link onClick={forceReload} to="/my-path-that-does-not-reload">
   Reload Page
</Link>

That worked for me for the Link and HTML button tag

Upvotes: 0

Bryan Lumbantobing
Bryan Lumbantobing

Reputation: 693

I don't know if react-router already solved this issue but in my case. I make a new route with pathname refresh that go back when first time rendering the component

<Route
    path="/refresh"
    exact
    component={() => {
       useEffect(() => history.goBack(), []);
       return <></>;
    }}
 />

So when I want to refresh the route. I just push to refresh routes and then it go backs then rendering a new reload result;

Upvotes: 2

Rajesh Sharma
Rajesh Sharma

Reputation: 121

This is how I achieved it :

if (currentUrl == newUrl) {
    props.history.push("/temp");
    props.history.goBack();
}

Upvotes: 2

Alberto Piras
Alberto Piras

Reputation: 537

You could use this little trick. Push a new path in the history like history.push('/temp') and immediately call the history.goBack()

Here the example:

Create an history and pass it to the router:

import { createBrowserHistory } from "history";

export const appHistory = createBrowserHistory();

<Router history={appHistory}>
  <Route exact path="/" component={Home} />
  <Route path="/about" component={About} />
</Router>

then somewhere in your app, change the history:

appHistory.push('/temp');
appHistory.goBack();

In this way the route will "remain" the same, and will be refreshed.

Upvotes: 5

Dapeng
Dapeng

Reputation: 11

Here is my solution with react-router-dom's "Redirect":

<Route key={props.notifications.key} path={props.notifications.path} exact render={() => <Redirect to={props.notifications.path + "/update"}/>}/>
<Route key={props.notifications.key + "/update"} path={props.notifications.path + "/update"} exact render={() => <props.notifications.component apis={props.notifications.apis}/>}/>

Upvotes: 1

Alexey Kutalo
Alexey Kutalo

Reputation: 241

Only this worked for me:

reloadOrNavigate = () => {
  const { history, location } = this.props;
  if (location.pathname === '/dashboard') {
    history.replace(`/reload`);
    setTimeout(() => {
      history.replace(`/dashboard`);
    });
  } else {
    history.push('/dashboard');
  }
};

The answer is similar to the previous one but I needed to add setTimeout function in order to make it work. In my case, I had to refresh the current URL by clicking the logo if I'm on the /dashboard page. First, it goes to extra route /reload (the name is up to you) and then immediately returns. The page becomes white for less than a second and appears with reloaded data. No reloading in browser occurs, it is still SPA which is good.

Upvotes: 1

Zach Taylor
Zach Taylor

Reputation: 289

I solved this by pushing a new route into history, then replacing that route with the current route (or the route you want to refresh). This will trigger react-router to "reload" the route without refreshing the entire page.

if (routesEqual && forceRefresh) {
    router.push({ pathname: "/empty" });
    router.replace({ pathname: "/route-to-refresh" });
}

React router works by using your browser history to navigate without reloading the entire page. If you force a route into the history react router will detect this and reload the route. It is important to replace the empty route so that your back button does not take you to the empty route after you push it in.

According to react-router it looks like the react router library does not support this functionality and probably never will, so you have to force the refresh in a hacky way.

Upvotes: 14

Kwun Yeung
Kwun Yeung

Reputation: 130

I have the same problem and I have no clue how the refresh does. My solution is to do following two steps.

  1. push new path to history
  2. reset all states

Then the DOM will rerender with your route.

Upvotes: 2

Related Questions