-1

I have 3 functional components and I'd like to pass & manipulate data through useRef.
I am adding this onClose method to current property in one of my component.

const onClose = () => {
    setButtonColor(buttonColor);
};

ref.current = {
    clearSwitchStateOnClose: onClose,  
};

I am calling that method in another component.

ref.current.clearSwitchStateOnClose();

I am receiving this error,

Uncaught TypeError: ref.current.clearSwitchStateOnClose is not a function
Chandler Bing
  • 410
  • 5
  • 25
  • This question looks like xy problem https://xyproblem.info/. Notice that refs assigned on first render, so you might call your function on mount. Finally, you should just share a reproducible example in codesandbox, refer to [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Dennis Vash May 02 '22 at 12:17
  • @Inder Notice that you have dedicated API for this. https://reactjs.org/docs/hooks-reference.html#useimperativehandle – Dennis Vash May 02 '22 at 12:25
  • @DennisVash Got it. – Inder May 02 '22 at 12:29

1 Answers1

0

I was calling this method ref.current.clearSwitchStateOnClose(); but with that I was also mutating ref. I guess that was causing the issue.
It was something like this,

ref.current = {
    showModal: false,
    modalResponse: null,
};
ref.current.clearSwitchStateOnClose();

After doing this, it is working fine.

ref.current.clearSwitchStateOnClose();
ref.current = {
    showModal: false,
    modalResponse: null,
};

Sorry for not sharing the entire scenario of this situation.

Chandler Bing
  • 410
  • 5
  • 25