5

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.

1
  • 1
    Go ahead and use context(trust me it's easier than you think) or uplift your state. window isn't going to persist your data if you reload the page. Commented Mar 1, 2020 at 15:14

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah actually it makes sense now. Thank you for your answer
No problem man, feel free to vote the answer if you feel like 😉
The question in regards to how to access window variable in reactjs. I'd suggest attempting that answer with the warning in regards to its use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.