react-native-bottom-sheet icon indicating copy to clipboard operation
react-native-bottom-sheet copied to clipboard

Updating state causes methods on bottom sheet to stop working

Open tom751 opened this issue 6 years ago • 4 comments

Bug

I have some state updates I need to do in my component when I want my bottom sheet to be opened, however when I do this my call to bottomSheetRef.current?.snapTo(1) no longer works. If I comment out the state update then it starts working again. The order in which the state update and calling the snapTo method makes no difference either. I have also tried using bottomSheetRef.current?.expand() and it has the same issue.

Environment info

Library Version
@gorhom/bottom-sheet 1.2.0
react-native 0.63.2
react-native-reanimated 1.13.0
react-native-gesture-handler 1.8.0

Steps To Reproduce

  1. Add a function which updates some state on the component and then call one of the methods on the bottom sheet ref
  2. Trigger the function
  3. State is updated but the method on the bottom sheet is not called
  4. Comment out the state update and trigger the function
  5. The method on the bottom sheet now behaves as expected

Describe what you expected to happen:

  1. The method on the bottom sheet should be called regardless of component state update

Reproducible sample code

import BottomSheet from '@gorhom/bottom-sheet';
import React, {useMemo, useRef, useState} from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';

const App = () => {
  const [counter, setCounter] = useState(0);
  const bottomSheetRef = useRef<BottomSheet>(null);
  const snapPoints = useMemo(() => [0, '90%'], []);

  const openBottomSheet = () => {
    // comment out setCounter and the bottom sheet opens as expected
    setCounter((prev) => prev + 1);
    bottomSheetRef.current?.snapTo(1);
  };

  return (
    <View style={styles.container}>
      <Button onPress={openBottomSheet} title="Open bottom sheet" />
      <BottomSheet ref={bottomSheetRef} snapPoints={snapPoints}>
        <Text>Hello</Text>
      </BottomSheet>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 24,
  },
});

export default App;

tom751 avatar Sep 10 '20 10:09 tom751

@tom751 , thanks for reporting this issue, I'll look into it later tonight 👍

gorhom avatar Sep 10 '20 12:09 gorhom

solved with v1.2.2 🎉

gorhom avatar Sep 15 '20 13:09 gorhom

Could you also fix it with current.expand() when rerendering?

levranger avatar Sep 22 '21 10:09 levranger

Wrap the entire component under useMemo solves this:

const Sheet  = useMemo(()=> <ButtomSheetModal>{children}</ButtomSheetModal>, [])
return <Sheet/>

johnsonfash avatar Dec 01 '23 01:12 johnsonfash