Muhammed Shahid
Muhammed Shahid

Reputation: 21

How to access the variables inside a function imported from another page in React?

My goal is to send a large string or an obj to another page on clicking a card. I tried sending the string through Link. But it can't be done since it has more than 4000 characters. So I decided to store the string to a variable inside a function on clicking the card and export the function to the other page. I successfully did it. My question is that: How can I access the variable inside the imported function on the other page?

I tried const {variable} = importedFunction(). But when i console logged the variable, it says undefined.

Page-1

export const handleClick =(obj)=> {
  const objVar= obj  
} 


Page-2

import handleClick from '../../NewsWithSidebar/NewsWithSideBar'

function Single() { 

 const {objVar}= handleClick()
 console.log(objVar) /*(but the console is showing undefined)*/

);

Upvotes: 1

Views: 3648

Answers (1)

Quentin
Quentin

Reputation: 943562

You can only access a variable if it is defined inside the scope you are working in or one of its ancestors.

You can't pull in a function from outside those scopes are read variables from inside it.


const {objVar}= handleClick()

For this syntax to work, the function has to return an object with an objVar property that you can destructure.

const handleClick = () => {
  const something = {
    objVar: 1234
  };
  return something;
};

const {
  objVar
} = handleClick()

console.log(objVar);

Upvotes: 1

Related Questions