Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass function that needs to be defined in useEffect to another component in ReactJS

I have a function:

const onReset = ()  => {
      setElements(initialElements);
      //console.log("reset clicked");
    };

The problem is initialElements must be defined inside a useEffect block. Moreover, initialElements have specific functions that are defined in the useEffect block.

How do I defined a function so that I can pass onReset to a child component like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  <Sidebar onSave={onSave} onRestore={onRestore} onReset={onReset} setElements={setElements} removeElements = {removeElements} onDownload={onDownload} 
                onHandleChange={onHandleChange}/>

>Solution :

Well, it seems a simple misunderstanding of the code example you’re working with in the React Flow library. As pertains to scope, specifically.

Although the example declares onChange in the useEffect method, it never attempts to call onChange outside the scope of useEffect, which is what you were attempting to do.

In the setElements state update, which is within the useEffect method, notice this object:

{
    id: '2',
    type: 'selectorNode',
    data: { onChange: onChange, color: initBgColor },
    style: { border: '1px solid #777', padding: 10 },
    position: { x: 300, y: 50 },
  },

This gets passed to the component, but onChange is never directly called outside useEffect, so it never violates any scoping rules.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading