1

I have to pass a function to another component using Link

    testFavorite=()=>{
        console.log("work")
    }

    <Link 
       to={{
       pathname: '/popular',
         state:{
            testFavorite: this.testFavorite
         }
       }}>
   Popular</Link>

This is how I call a function this.props.location.state.testFavorite();

This is giving me this error

DataCloneError: Failed to execute 'pushState' on 'History': () => testFavorite() could not be cloned.

Umar Javed
  • 55
  • 8
  • this code is not sufficient to clarify the issue. you need to provide more information, probably how you declare you `` for popular path, and it's component. you could consider adding a sandbox with the reproduced error. – buzatto Apr 01 '21 at 22:54
  • You can find the code here https://codesandbox.io/s/blazing-resonance-qgi2m?fontsize=14&hidenavigation=1&theme=dark&file=/src/Header.js – Umar Javed Apr 01 '21 at 23:08
  • Moreover, below is To the point question function loadUser(){ console.log("load")} Upon executing this is giving me an error – Umar Javed Apr 01 '21 at 23:11
  • it seems that state is serialized and functions can't be serialized: [related question](https://stackoverflow.com/questions/50618225/uncaught-domexception-failed-to-execute-pushstate-on-history-function) – buzatto Apr 02 '21 at 01:10
  • Hey @UmarJaved , Did you get the solution of this. I am having the same problem. Please share the solution. – Salman Ahmad - Mean Developer May 12 '21 at 08:51

1 Answers1

2

In <Link /> component, I replace "state" property with "data" property. And it works now!

<Link 
    to={{
       pathname: '/popular',
       data:{
          testFavorite: this.testFavorite
       }
    }}
>
   Popular
</Link>

It will be accessable with this: this.props.history.location.data

Ali Amini
  • 172
  • 2
  • 14
  • Where did you find this solution? it's not even in Documentation, stackoverflow – Umar Javed Apr 02 '21 at 13:52
  • Yes, the documentation is not complete. I only try to see what happen if I use "data" property because I've seen already in routes, we use "data" prop for passing data to a route. – Ali Amini Apr 03 '21 at 07:04
  • @Ali Amini It's not seems to be working on page reload. Please help i am having the same problem. I need to pass the a function from link and want to call it into another page like this this.props.location.state.myFunction. – Salman Ahmad - Mean Developer May 12 '21 at 08:47