I am making a simple React application in which there is a app.tsx file with the code as follows,
export default function App() {
const initializeData = () => {
const dataScript = document.createElement("script");
dataScript.type = "text/javascript";
dataScript.textContent = `
let data = { 'name': "" };`;
document.head.appendChild(dataScript);
};
React.useEffect(() => {
initializeData();
}, []);
return (
<div className="App">
{console.log(data)}
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
-> Where initializeData method will intialize a global data and that will be available for all other pages (considering all components will be called from here in app.tsx ).
-> Calling the method from useEffect lifecycle hook like,
React.useEffect(() => {
initializeData();
}, []);
-> Trying to console.log the data in template like,
return (
<div className="App">
{console.log(data)}
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
Error:
This line {console.log(data)} throws the error as data is not defined
Requirement:
Need to make a variable declaration in global level so those variables would be available for all files.
Keeping this in mind only I have tried assigning it in head tag inside script tag but this shows error in typescript.
Please help me on how to assign a global variable and access it inside any files..
metricswhich you don't seem to be doing above. (My guess is that it's doing that in order to set up a context thatMetricsElements and such can use, but that's just a guess.) But I don't want to get into a back-and-forth about whether you need a global variable. Your question was about whydatadoesn't exist, which I've answered below. Happy coding!