Get React Router params before rendering component

Hey guys,

I’m trying to set up basic user profile pages which will be accessed like this : example.com/username

I’m trying to access the incoming route params (not a query string) and pass them to a Meteor Method which returns the user data and assigns it to the meta prop before rendering my user profile component, but I can’t seem to access the params.

All of my apps routes are set up in app.js and switch based on whatever url is entered :

<Switch>
  <Route exact path="/:username" render={props => <UserProfile {...props} meta={this.getProfile(this.props.match.params.username)} />} />
  ...
  ...
</Switch>

But it always returns “undefined”.

It works if I hard code a username :

<UserProfile {...props} meta={this.getProfile("someuser")} />

So I know my logic is all working, but I just can’t seem to be able to extract the username parameter from the incoming url.

Is it not possible to get a named parameter in this way before the component is rendered or am I just doing it wrong?

The matched parameters will be automatically passed inside the UserProfile component. Therefore, you need to move your logic of accessing the value of this.props.match.params.username inside UserProfile

Yes that’s where I had them originally but it was unworkable.

The user profile component renders different views based on whether a valid user is found or not.

It was working, but it would would flash up the “no user found” view for a split second before re-rendering the component with the user data and then showing the correct view.

I thought trying to pass the user data as props, into the component before it was initially rendered, would solve this issue and avoid the re-render problem, but I just can’t seem to extract the url parameter?

Always remember that Meteor method calls (and subscriptions) are asynchronous i.e. there will be a time in between fetching the data from the server and then getting the data when the data is empty.

If you wanted to handle the case, then add a state variable (if method call) and name it like dataFetched and set it initially as false. Set the dataFetched state to true once you completed the method call.

Then when you display the user profile, add the check like if (this.state.dataFetched)

That’s a good idea, didn’t think of delaying the render in this way.

Many thanks, will try that now :wink:

Yep that works. Thanks again!