Search code examples
reactjsglobal-variablesglobal

How to access global (window.) variable in React JS


I’m using React JS. I have login page which receives data as a response from the end point. I’m storing different components from the response in a window. variables because they must be accessed in different components. And this only works initially when the new component is loaded, after it’s refreshed the window. variable becomes empty.

This is my login component:

handleSubmit(event) {
event.preventDefault()

axios
  .post("EDN POINT LINK",
    {
      email: this.state.email,
      password: this.state.password

    })
  .then((response) => {

    console.log(response);

    // STORING ID
    window.id = window.responseDetails.map(
      mID => mID.id
    )
    console.log('ID is: ' + window.id);

    // STORING TOKEN
    window.token = window.responseDetails.map(
      mToken => mToken.token
    )
    console.log('TOKEN is: ' + window.token);

    // STORING ERROR
    window.error = window.responseDetails.map(
      mError => mError.error
    )
    console.log('ERROR is: ' + window.error);

And this is the component where I access the window. variable:

 render() {

    console.log(window.id)
    return (

    )
}

If I had more time I would implement something like Redux or Context but Unfortunately I don't because I am fairly new to React JS.


Solution

  • Please don't store persisting data in window!

    Window is global, but its scope is related to a fresh page load.

    To have consistent data, you should consider persistent storages like localStorage, sessionStorage and cookies.

    Give a look here for more examples What is the difference between localStorage, sessionStorage, session and cookies?