1

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...

Saud Anjum
  • 208
  • 2
  • 12

2 Answers2

2

Regarding to documentation fetching data in componentDidMount is a right choice

Maksym Bezruchko
  • 1,223
  • 6
  • 23
1

I would recommend using hooks if you aren't, but otherwise a possible way to handle what you want would be to wrap each route's component in the same component, and put the useEffect (hook version) or componentDidMount functionality in that component. That way the same logic will fire off each time any route that is wrapped in it is rendered.

Tommy Treb
  • 11
  • 1