Saud Anjum
Saud Anjum

Reputation: 246

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

Upvotes: 1

Views: 1962

Answers (2)

Maksym Bezruchko
Maksym Bezruchko

Reputation: 1258

Regarding to documentation fetching data in componentDidMount is a right choice

Upvotes: 2

Tommy Treb
Tommy Treb

Reputation: 11

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.

Upvotes: 1

Related Questions