Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass callback function as prop to a different route using react-router

I'm attempting to pass a function to be used as a callback in a different route. I know it's possible to do this:

import { useHistory } from "react-router-dom";

const FirstPage = props => {
    let history = useHistory();

    const someEventHandler = event => {
       history.push({
           pathname: '/secondpage',
           state: { detail: 'some_value' }
       });
    };

};

but I get this error when I try pass a callback function like this:

my code with callback:

    const someEventHandler = event => {
       history.push({
           pathname: '/secondpage',
           state: { my_callback: selectedPlaylist }
       });
    };

error:

DataCloneError: Failed to execute 'pushState' on 'History': selectedPlaylist => {
       ....
  }

Is this just something that cannot be done since it's a reference to a function and not necessarily state? Is there a workaround? I'm not able to find any resources similar to this. Thanks in advance!

like image 970
Andre Tran Avatar asked Apr 10 '26 03:04

Andre Tran


1 Answers

MDN says:

The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.

A function cannot be cloned or serialized. What you want to do is better be passed as props. Using state object on history is very weird. Example:

function FirstPage() {
  // ...
  return (
    <>
      <Link to='/secondpage'>go to second page</Link>
      <Route
        path='/secondpage'
        render={() => <SecondPage myCallback={selectedPlaylist}}
      />
   </>
  );
}

If you expand more on what you want to accomplish, it'll get easier to help.

like image 119
Sam R. Avatar answered Apr 12 '26 19:04

Sam R.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!