1

So, I'm having a hard time passing data between two unrelated components. I have this code below, but I don't know how to receive it from the other component

<Button
   className='search__button'
   variant="contained"
   color="primary"
   size="large"
   component={Link}
   to={{
     pathname: "/home",
     state: { data: results }
   }}
>

I want to pass the variable "results" which is a Map of a string and an object Book (Map<string, Book>) to a component. Basically, my question is, how do I retrieve data in my Home component?

Thank you

2

1 Answer 1

1

When sending state with route transitions you can access it on the location object of the receiving route in a few different ways:

  1. In the case of functional components you can use the useLocation hook.

     const { state } = useLocation();
     // access state.data
    
  2. If the component is rendered by a Route on the render, component, or children prop then route props will be passed to the component. location will be a prop. Or you can decorate the component with the withRouter have have the route props of the closest matching Route passed as props.

     const { location: { state } } = this.props;
     // access state.data
    

    or

     const { location: { state } } = props;
     // access state.data
    
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I receive the data but not on the first try. When I press the button for the 2nd time, that's when I receive the data, where is there a delay ?
@PatrickYoussef Does clicking this button also trigger some asynchronous callback, i.e. does it trigger some data fetching or similar?
No, at first, I initialize "let results: Filters = {}" (Filters is an interface I created). Then clicking the button calls a function that changes the variable "results". And then as you can see, I have a button that sends "results" to /home

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.