Reputation: 4160
I am learning React and I dont understand how to make something like global aplication state. I made a window.appState variale but I am not able to get the appState inside the components. It throws me an error appState is undefined. appState initiliazation looks like:
import React from 'react';
import ReactDOM from 'react-dom';
import './assets/index.scss';
import App from './App';
import {
BrowserRouter as Router
} from "react-router-dom";
let appState = {
accessToken: ''
}
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
document.getElementById('root')
);
and if I try to access appState in component it is undefined.
class Home extends React.Component
{
constructor(props)
{
super(props)
// window.appState is undefined???
if( ! window.appState.accessToken ) this.props.history.push('/login')
}
.....
}
What am I doing wrong? Thanks a lot.
Upvotes: 1
Views: 766
Reputation: 80041
Setting let appState = {}
sets that in the scope of the file. If you want to set it on window
so that it is global you would instead do window.appState = {}
.
Upvotes: 1