Search code examples
react-nativees6-promise

Why do I get the error message "undefined is not a function" when trying to cancel a promise on press?


I have a sleep function that resolves after a timeout and that is awaited for in a async function called go. The function go is called by pressing on a touchableOpacity.

In some cases I want to reject the promise before it resolves by pressing on a touchableOpacity. For that reason I implemented a function to reject the promise called promiseReject.

Now if a call the go function and then try to cancel the promise by calling promiseReject an error is thrown saying: "undefined is not a function"

I appreciate any help to resolve this issue. Thank you in advance.

let promiseReject

const sleep = seconds => new Promise((resolve, reject) => {
  const timeoutId = setTimeout(resolve, seconds * 1000)

  promiseReject = () => {
    clearTimeout(timeoutId)
    reject()
  }
})

const go = async () => {
  await sleep(10)
}

<TouchableOpacity
  onPress={() => {
    go()
  }}
>
</TouchableOpacity>

<TouchableOpacity
  onPress={() => {
    promiseReject()
  }}
>
</TouchableOpacity>

Solution

  • Use useRef to store a function to avoid clearing when rendering.

    useRef is a React Hook that lets you reference a value that’s not needed for rendering.

    const cancel = useRef(null);
    ...
    cancel.current = () => { ... };
    ...
    cancel.current()
    

    See Referencing a value with a ref for details.