React JS How to pass data between pages in Hook ( useEffect)

Viewed 8325

I am trying to pass one data object to another page, but I can't fetch the data on the second page. below code is I am using

The first page pass the data in LINK

 <Link to={{ pathname: `${path}/users/${organization.id}`,
                                            data: organization
                                        }}>  <img src={config.s3Bucket + "/" + organization.logo} />
 </Link >

Here I am passing the object in the 'data' parameter

Second page

import React, { useState, useEffect } from 'react';
function UserList({ history, match }) {
const { path } = match;
const { id } = match.params;
const [organization, setOrganization] = useState(null);

// const { data } = this.props.location

useEffect(() => {
    
    // console.log(location.data);

}, []);  }   export { UserList };

I have tried the 'location.data' and 'this.props.location' but I can't fetch the data, please help me to solve this issue.

2 Answers

You can do it like this

<Link to={{ pathname: `${path}/users/${organization.id}`, state: organization}}>
   <img src={config.s3Bucket + "/" + organization.logo} />
 </Link >

and in the Second Page

import React, { useState, useEffect } from 'react';
import {useLocation} from 'react-router-dom';

function UserList({ history, match }) {
  const { path } = match;
  const { id } = match.params;
  const [organization, setOrganization] = useState(null);

  const { state } = useLocation();

  useEffect(() => {
    console.log(state);
  }, []);
}   

export { UserList };

use withRouter

import { withRouter } from "react-router-dom"







export default withRouter(ComponentName)
Related