mycellius
mycellius

Reputation: 598

React: how to remount a sibling component to re-run componentDidMount?

In my application, a user has multiple.. let's say 'dogs'. The currently selected dog appears in the header, and can be changed through the header's dropdown menu. Upon selecting their new dog, it marks it as primary: true on the backend, and I make the corresponding header UI update. From that point onwards, all requests to the backend return results for the primary dog.

I have a Layout.jsx component that looks like this:

<Header />
<div>
  {this.props.children}
</div>

In this.props.children, I render an index page for multiple different resources, i.e an example of a child component might be TreatsContainer where a network request is made in componentDidMount to /treats, and the results are rendered within my layout.

The problem I am facing is that when a user changes their dog in the header component, I'd like the other components to re-run the same network request that they are making in componentDidMount, so that the newly selected dog's data is shown. I have Redux implemented in a couple places within the application, but I'd like to not store all data in the global state tree, because there's no limit to how many resources the user can create. What I mean by this is I don't want all data from /treats, /toys, /foods, etc. in a bunch of arrays. What would be a good approach to handling this situation?

Upvotes: 2

Views: 648

Answers (2)

Luke Willis
Luke Willis

Reputation: 8580

I agree with @palsrealm's suggested approach, but here's one alternative if you're using :

Put the primary dog's Id in the URL,

<Route path="/:dogId" component={DogIndex} />

then when the user selects a primary dog, you can route to the index page.

<Link to=`/${selectedDogId}` />

Then your component (DogIndex) will mount and componentDidMount will fire.

Upvotes: 1

palsrealm
palsrealm

Reputation: 5243

I am not sure I understand your question fully but I will still try to answer it to the best of my abilities. From what I understood, you have a Header component which sets the primary dog. And you want your child component to get fresh data from the backend when this primary dog gets changed.

The way I would achieve this is

  1. Store the current primary dog in the Redux store and fire an action in your Header component when it changes, to update it.
  2. From each child component, access the primary dog from the store as props using mapStateToProps
  3. In each child component, do a call to the backend to fetch the relevant data in componentWillReceiveProps when this.props.primaryDog != nextProps.primaryDog

Upvotes: 3

Related Questions