Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variable made in componentDidMount

I have a variable that I'm creating in componentDidMount() and I'd like it to be available in componentDidUpdate(). Any thoughts? Code looks like this:

class Example extends Component {
  componentDidMount() {
    const myVariable = 'this thing';
  }

  componentDidUpdate() {
    // I'd like my variable to be accessible here
    console.log(myVariable);
  }

  render() {...}
}
like image 973
jasonetco Avatar asked Jun 27 '16 16:06

jasonetco


People also ask

Is componentDidMount called only once?

componentDidMount() only runs once after the first render. componentDidMount() may be called multiple times if the key prop value for the component changes. componentDidMount method is used for handling all network requests and setting up subscriptions during the mounting phase.

What triggers componentDidMount?

The componentDidMount() method will be triggered as soon as the component is mounted or inserted into the DOM. The basic syntax to use componentDidMount() is looks like this. This method used widely by developers because it loads immediately once the component is mounted.

What happens in componentDidMount?

The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.

Can I call a function in componentDidMount?

There is some fundamental misunderstanding here, you can still call the functions inside componentDidMount , however you should not define them inside it.


1 Answers

Save it to the component then.

componentDidMount() {
    this.myVariable = 'this thing';
}

componentDidUpdate() {
    // I'd like my variable to be accessible here
    console.log(this.myVariable);
}

Also, as @Gosha Arinich helpfully pointed it out - be aware that if you do plan to re-use this variable throughout the component's lifecycle and update it and/or render it - it is best placed into the state of the component (this.state).

like image 85
Elod Szopos Avatar answered Sep 19 '22 00:09

Elod Szopos