Search code examples
reactjsfunctionreact-routerreact-router-domreact-lifecycle

on route change in react js call a function


Bellow is the App.js file. when ever I click on any of the nav bar the selected route is rendered.

function App() {
    return (
        <div>
            <Layout>
                <Switch>
                    <Route path="/" exact component={Home} />
                    <Route path="/success-cards" component={Success_Cards} />
                    <Route path="/failure-cards" component={Failure_Cards} />
                    <Route path="/snap-photo" component={Snap_Photo} />
                    <Route path="/all-cards" component={All_Cards} />
                    <Route path="/user-guide" component={User_Guide}/>
                    <Route path="/rejected-cards" component={Rejected_Cards} />
                </Switch>
            </Layout>
        </div>
    );
}

export default App;

What I want is when I am clicking on some nav bar then it should call an API as a default to fetch few data. The challenging part is what method should I use to achieve on route change call a function to fetch data. Can anyone please help. I have tried comoponentDidMount, componentShouldMount etc...


Solution

  • Regarding to documentation fetching data in componentDidMount is a right choice