4

I have a really weird issue, I have two components (both navigation routes) which share the same higher-order component that keeps the posts as state. One component can link to the other by passing a post slug to the route as a parameter, this component, in turn, scrolls a flaList to the correct index:

  findIndexBySlug = memoizeOne(
    (postsArray, selectedPostSlug) => postsArray.findIndex(
      post => post.slug === selectedPostSlug,
    ),
  );

  constructor(props) {
    super(props);
    this.shouldScrollToPost = this.shouldScrollToPost.bind(this);
    this.scrollToIndex = this.scrollToIndex.bind(this);
    this.flatListRef = React.createRef();
  }

  componentDidMount() {
    this.shouldScrollToPost();
  }

  componentDidUpdate() {
    this.shouldScrollToPost();
  }

  shouldScrollToPost() {
    const { navigation } = this.props;
    const selectedPostSlug = navigation.getParam('selectedPostSlug');
    console.log('shouldscrollto', selectedPostSlug);
    if (selectedPostSlug) {
      const { posts } = this.props;
      const { postsArray } = posts;
      const selectedPostIndex = this.findIndexBySlug(
        postsArray, selectedPostSlug,
      );
      this.scrollToIndex(selectedPostIndex);
    }
  }

  scrollToIndex(index) {
    if (this.flatListRef.current) {
      console.log('scrolling to ', index)
      this.flatListRef.current.scrollToIndex({ index, animated: false });
    }
  }

In both the first mount (componentDidMount) and subsequent calls (componentDidUpdate) all the console.log fire (including the one that checks for the flatListref) but, when called the first time in componentDidMount no scrolling occurs, in componentDidUpdate it does actually scroll!

Why?

It's driving me insane, even read the Dan Abramov post about the availability of refs (componentDidMount called BEFORE ref callback) and the flatList is the only rendered component (in fact the ref is always available).

Any help greatly appreciated.

Thanks

0plus1
  • 4,475
  • 12
  • 47
  • 89

0 Answers0