iiian
iiian

Reputation: 413

v6 react-router returns `null` state in location when state given a function property

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:

Things I think would be better avoided:

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!

Upvotes: 1

Views: 1719

Answers (1)

iiian
iiian

Reputation: 413

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.

Upvotes: 1

Related Questions