1

I am doing a nested routers layout. I have a parent component that needs to render a list of N children. Additionally, I want to pass a function (id: string) => Observable<X> from parent to child. Currently, I am doing:

// parent.tsx

function getStream(id: string): Observable<X>; // assume exists

function Parent() {
  const child_links = children_data.map(child_data => (
    <Link
      to={...}
      state={{ child_data, getStream }}
    />
  ));

  ...
  // return some output with `child_links` embedded
}
// child.tsx
import { useLocation } from 'react-router';

function Child() {
  const location = useLocation();

  // The issue I am facing:
  // returns { child_data: {...} } if I choose to omit `getStream` in `Parent`;
  // returns `null` when `getStream` included; expected `getStream` to exist and be function I passed
  console.log(location.state);

  // some arbitrary rendering
}
//index.tsx, where Router defined:

ReactDOM.render(
  <div>
    <BrowserRouter>
      <Routes>
        <Route path='/' element={<Parent />}>
          <Route path='children/:child_id' element={<Child />} />
        </Route>
      </Routes>
    </BrowserRouter>
  </div>,
  document.getElementById('root')
);

Other ridiculous things I have tried:

  • Wrapping the function in an object, passed through constructor. Effect: causes same null state problem.
  • Wrapping the function in an object, as a method. Effect: does not cause null state, but the associated property of state ends up just being an empty object. this tells me that react-router is likely doing less-than-smart hash object cloning.

Things I think would be better avoided:

  • Just creating a static controller object that serves up the Observable
  • Using the Context system from react

Am I abusing state here? If Links are to be used in a nest router setting, am I expected not to share upstream state with downstream components?

Thanks!

3
  • This part of the docs might help: reactrouter.com/docs/en/v6/upgrading/v5#note-on-link-to-values
    – srWebDev
    Jan 18, 2022 at 21:27
  • 1
    Functions are not serializable, they can't be sent through route state. You could certainly pass the id in route state for the child to invoke getStream with.
    – Drew Reese
    Jan 18, 2022 at 21:31
  • 1
    That seems like the most sensible solution, Drew. As I look at it more. Thanks for the second set of eyes.
    – iiian
    Jan 18, 2022 at 21:48

1 Answer 1

1

As mentioned by @DrewReese, functions are not serializable, and thus cannot be sent through route state. Therefore, my solution to this issue is simply to introduce a getStream function in a location accessible to the Child.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.