NealVDV
NealVDV

Reputation: 2532

componentDidMount fires twice when using TransitionGroup for animation

I'm currently using react-transition-group in conjunction with react-router-dom to animate route changes and this is working fine.

The only issue I'm having is that when switching routes and I need to send or fetch some data in the componentDidMount life-cycle hook, it get fires twice. I'm fairly sure this is due to the react-transition-group but I was wondering if there is an obvious solution to this issue.

I discovered this as it was inserting an entity in the database twice, which is far from the intended behavior.

Example of transition with logging in componentDidMount enter image description here

Upvotes: 0

Views: 1779

Answers (2)

johnny
johnny

Reputation: 343

Here's the snippet from the github issue so you don't have to click through.

Add location to Switch: <Switch location={location}>

<TransitionGroup component="main">
  <CSSTransition
    key={location.pathname}
    timeout={timeout}
    exit={false}
    classNames="fade">
    <Switch location={location}> // <- Here it is!
      <Route exact path="/" component={Home} />
      <Route path="/blog" component={BlogList} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
      <Route component={NotFound} />
    </Switch>
  </CSSTransition>
</TransitionGroup>

Upvotes: 1

NealVDV
NealVDV

Reputation: 2532

I've found that it is an issue with my Switch component, see this github issue

Basically you need the location prop in your wrapped Switch component.

Upvotes: 5

Related Questions