react-native-reanimated icon indicating copy to clipboard operation
react-native-reanimated copied to clipboard

Refactor `measure()` to handle `try` internally

Open naftalibeder opened this issue 2 years ago • 0 comments

Description

Allows measure() to handle exceptions internally, and return null if the measurement cannot be made.

The impetus for this is occasional hard crashes when calling measure, seemingly due to a view not yet having loaded, but not fixable in the enclosing app with a null check on the ref, a try block, etc. - once the JS passes a value to the native method _measure, an invalid argument will cause a crash.

This way, the caller:

  • is guaranteed that calling measure will not cause the enclosing app to crash (even in a try block)
  • does not need to consider the various reasons why measurement might fail (uninitialized ref, component out of view, etc.)
  • can cleanly check the return object, instead of needing to evaluate an arbitrary property on it (e.g. if (isNaN(measured.x))

Note: I still occasionally get a crash that reports that the native _measure method is not defined. I haven't been able to fix this, because it's impossible to do a falsy check - if it doesn't exist, even a conditional or console.log referencing _measure (even in a try) causes a hard crash. Any ideas for how to check this?

Changes

  • Return early if viewTag is -1 (invalid)
  • Make early returns return null instead of throwing
  • Fix incorrect RefObjectFunction import path
  • Fix example assuming non-null measure response
  • Remove unneeded ignore comments
  • Fix "indefined" misspelling

Test code and steps to reproduce

Simply run FabricExample/src/MeasureExample.tsx.

Checklist

  • [X] Included code example that can be used to test this change
  • [X] Updated TS types
  • [ ] Added TS types tests
  • [ ] Added unit / integration tests
  • [X] Updated documentation
  • [X] Ensured that CI passes

naftalibeder avatar Aug 08 '22 19:08 naftalibeder