how to fetch a nested resource for every component in React router dom route

Viewed 222

So I have some nested routes that look like this:

<Switch>
  <Route exact path={"/"}>
    <HomepageContainer />
  </Route>
  <Route path={"/users"}>
    <UsersContainer />
  </Route>
  <Route path={"/users/new"}>
    <NewUserContainer />
  </Route>
  <Route path={"/users/:userId/edit"}>
    <EditUserContainer />
  </Route>
  <Route path={"/users/:userId/comments"}>
    <UserCommentsContainer />
  </Route>
  <Route path={"/users/:userId/comments/:commentId"}>
    <UserCommentContainer />
  </Route>
  <Route render={() => <Redirect to={"/"} />} />
</Switch>

Three of which have a userId in the URL params and inside those components I fetch a user inside of a useEffect hook.

Is there a way for react-router-dom to allow me to do this fetch in a single place and make the result available to EditUserContainer, UserCommentsContainer and UserCommentContainer?

1 Answers

I've found a solution I'm happy with and not sure why I didn't think of it initially (still learning React!)

<Switch>
  <Route exact path={"/"}>
    <HomepageContainer />
  </Route>
  <Route path={"/users"}>
    <UsersContainer />
  </Route>
  <Route path={"/users/new"}>
    <NewUserContainer />
  </Route>
  <Route path={"/users/:userId/edit"} render={() => {
    <CurrentUserContainer>
      <EditUserContainer />
    </CurrentUserContainer>
  }} />
  <Route path={"/users/:userId/comments"} render={() => {
    <CurrentUserContainer>
      <UserCommentsContainer />
    </CurrentUserContainer>
  }} />
  <Route path={"/users/:userId/comments/:commentId"} render={() => {
    <CurrentUserContainer>
      <UserCommentContainer />
    </CurrentUserContainer>
  }} />
  <Route render={() => <Redirect to={"/"} />} />
</Switch>

Wrapping each of the nested user components in a parent CurrentUserContainer that will be responsible for doing the fetch and setting the state, making it available where needed.

Related