0

In my React component, I have a method populateData()

This method is called at various places in my Component. It is called from render, componentDidUpdate, componentDidMount etc.

Now, there is a special condition in the method populateData() which only needs to be executed when it is called from componentDidMount.

Is it possible to know which lifecycle method is the caller, without passing that as an argument to the method?

Example code for populateData():

const populateData = () => {
   //do something
   if(caller === 'componentDidMount') {
      //do this also
   }
}
Shaurya Mittal
  • 764
  • 1
  • 8
  • 19
  • Why not pass as an argument? – Moshe Sommers Jun 17 '21 at 20:53
  • I want to avoid the change to method signature as it is being called at many places which various args already – Shaurya Mittal Jun 17 '21 at 20:56
  • 1
    Unless there's a cleaner way, you could potentially [get the current stack](https://stackoverflow.com/questions/43236925/print-current-stack-trace-in-javascript) and read/parse it for the information you need. That seems like a bit of a hack though and could negatively impact performance. It *sounds like* this may be more of an XY Problem and your current stated goal may just be covering up a better long term solution, if perhaps a more involved one to implement. – David Jun 17 '21 at 20:56
  • 1
    How about adding an optional parameter iscomponentDidMount?:boolean ? Then you only need to update where it's called in componentDidMount – Moshe Sommers Jun 17 '21 at 20:59

1 Answers1

0

You can add a default parameter to check if it's being called from componentDidMount

const populateData = (isFromComponentDidMount = false) => {
    //do something
   if(isFromComponentDidMount ) {
      //do this also
   }
}

Then just pass in true when being called from componentDidMount

 componentDidMount(){
     populateData(true)
 }

Everywhere else your calling populateData can remain the same

Moshe Sommers
  • 1,466
  • 7
  • 11