flow icon indicating copy to clipboard operation
flow copied to clipboard

Problem with conditionally accessing ref values in Flow 0.54.1

Open kevanstannard opened this issue 9 years ago • 2 comments

I am wrapping access to a ref value in an if block.

Flow correctly recognises the guard for the first line in the block, but doesn't seem to recognise the guard for the second line in the block.

The following code shows the error (also works on flow.org/try):

// @flow

import * as React from 'react';

export default class MyComponent extends React.Component<*> {
  spanEl: ?HTMLSpanElement;

  componentDidUpdate() {
    if (this.spanEl) {
      this.spanEl.style.removeProperty('top'); // This is fine
      this.spanEl.style.removeProperty('left'); // This reports an error
    }
  }

  render() {
    return <span ref={el => this.spanEl = el}>Hello</span>;
  }
}

This produces the following errors:

11:       this.spanEl.style.removeProperty('left');
                      ^ property `style`. Property cannot be accessed on possibly null value
11:       this.spanEl.style.removeProperty('left');
          ^ null
11:       this.spanEl.style.removeProperty('left');
                      ^ property `style`. Property cannot be accessed on possibly undefined value
11:       this.spanEl.style.removeProperty('left');
          ^ undefined

kevanstannard avatar Sep 12 '17 21:09 kevanstannard

You invalidated your refinement of this.spanEl when you called this.spanEl.style.removeProperty('top') (though this invalidation will happen when you call any function). You should make a reference to this.spanEl:

if (this.spanEl) {
  const span = this.spanEl
  span.style.removeProperty('top')
  span.style.removeProperty('left')
}

jcready avatar Sep 13 '17 22:09 jcready

Thanks @jcready

kevanstannard avatar Sep 13 '17 23:09 kevanstannard