1

Actually I am initializing a variable in componentDidMount and from there printing its value on console. So in the console I am getting the value of variable but when I print the value of variable from render I am getting "undefined".

var data    //declaring a global variable
export default class Schemes extends React.Component{
  constructor(){
  super();
  this.response = response

  componentDidMount(){
    /* Some Computation*/
    if(localStorage.getItem('xyz')){
      data = response
    }
  }

  render(){
    console.log("In render", data);
  }
7
  • Can you post your code please? Also, did you initialise the variable in componentWillMount (or the constructor for a class)? If it's undefined, there might your problem. Commented Nov 29, 2017 at 11:50
  • i have tried intialising the variable inside the constructor Commented Nov 29, 2017 at 11:56
  • Please update the question with the class snippet, showing all what you are asking. Commented Nov 29, 2017 at 12:08
  • @brandNew I have updated the question Commented Nov 29, 2017 at 12:27
  • componentDidMount runs after the initial render – therefore accessing localStorage occurs after your render function attempts to log the data from localStorage. Commented Nov 29, 2017 at 12:37

1 Answer 1

3

Just tested this and it works, but i wouldn't use global variables. I would use state instead.

import React, { Component } from 'react'

var data = 'my data'

class Test extends Component {
    constructor(props) {
        super(props)
        this.response = 'my response'
    }
    componentWillMount() {
        localStorage.setItem('test', 'w00f')

        if (localStorage.getItem('test')) {
            data = this.response
        }
        data = this.response
    }
    render() {
        console.log(data) //my response
        return (
            <div></div>
        )
    }
}

export default Test

Here is a better version using state:

import React, { Component } from 'react'

class Test extends Component {
    constructor(props) {
        super(props)

        this.state = {
            data: null,
            response: 'got reponse'
        }
    }

    componentWillMount() {
        localStorage.setItem('test', 'w00f')

        if (localStorage.getItem('test')) {
            this.setState({ data: this.state.response })
        }
    }
    render() {
        console.log(this.state.data) //got reponse
        return (
            <div></div>
        )
    }
}

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

Comments

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.