Vincent Nguyen
Vincent Nguyen

Reputation: 1663

React ComponentDidMount being called multiple times

I am trying to make a fetch api call inside of AccountItem.js like so:

componentDidMount() {
    // I am calling console.log("item mounted"); here
    var url = "myurl" + this.props.portalId;
    fetch(url)
    .then(res => res.json())
    .then(data => this.setState({account: data.Items}));
}

Then inside my Home.js it renders:

componentDidMount() {
   console.log("home mounted");
}
render() {
    return (
      <div>
        Account Dashboard
        <AccountItem portalId={this.props.portalId}/>
      </div>
    );
  }
}

I am logging my fetch into the console and it is being called three times. The flow is I am on the login page (mounted once upon load), I login which redirects me to the home page which itself renders . At this point in my console I see:

Login mounted // initial load, now I click login Login mounted // Renders again then redirects to homepage Item mounted Home mounted Item mounted Home mounted Item mounted // Why is this happening 3 times?

I am new to react, please let me know if you need any more information.

Upvotes: 4

Views: 7256

Answers (1)

Vincent Nguyen
Vincent Nguyen

Reputation: 1663

Okay, the problem was in my Router I was rendering this:

<BrowserRouter>
                <div>
                    // Other routes here
                        <this.PrivateRoute path="/home" exact component={<Home .... />} />
                    </Switch>
                </div>
            </BrowserRouter>

And my private route was:

PrivateRoute = ({ component: Component, ...rest }) => (
                <Route {...rest} render={() => (
                    this.state.isAuthenticated
                    ? <Component {...this.props} portalId={this.state.portalId}/>
                    : <Redirect to="/" />
                )}/> 
            )

So the home was being rendered multiple times. I simply just swapped out the <Home /> inside the router to {Home}

Upvotes: 1

Related Questions