Home > database >  How to pass a callback without invoking ist?
How to pass a callback without invoking ist?

Time:07-20

I want to pass a callback function. At moment it gets called before it gets passed. What is wrong?

<MyComponent callback={()=> console.log(1)} isDirty ={true} setCallback={()=>{}} />

Declaration

export function MyComponent({ ...props} ) {
  const { setCallback, callback, isDirty } = props
  const cancelCallback = isDirty ? () => setCallback(callback) : callback

  return (
    <>

        <Button onClick={cancelCallback}>Cancel</Button>

    </>
  )
}

CodePudding user response:

I replicated it on my system and it doesn't get called. One common mistake is to pass a callback function like this:

callback={console.log(1)}

instead like this:

callback={() => console.log(1)}

With this mistake the callback function gets called immediately.

CodePudding user response:

you need to update your click handler function.

const cancelCallback = () => {
  isDirty ? setCallback(callback) : callback();
};
  • Related