Effect does not work when used in the Effects method

Viewed 23

I am trying to use a scroll effect but it is not working very well.

To scroll down the duration is respected, the effect works.

To scroll up, the duration is ignored, it rolls at once.

<TouchableOpacity
        onPress={() => setStateMenu(!stateMenu)}
        activeOpacity={10}
 >
...
</TouchableOpacity>


const [stateMenu, setStateMenu] = useState(false);
  const translateY = new Animated.Value(0);

  useEffect(() => {
    controlMenu();

  });

  function controlMenu() {
    if (!stateMenu) {//fechar Menu
      //alert('Fechando');
      Animated.timing(translateY, {
        toValue: 0,
        duration: 400,  
        useNativeDriver: true,
        //delay: 300,
      }).start();
    }
    else {//abrir Menu
      //alert('Abrindo');
      Animated.timing(translateY, {
        toValue: 800,
        duration: 400,
        useNativeDriver: true,
        //delay: 300,
      }).start();
    }
  }

When stateMenu is equal to false, the scrolling goes from 0px to 800px, respecting the time passed for duration, that's right. Now when stateMenu is true, the scrolling goes to 0px at once, not respecting 0.400 seconds.

1 Answers

Try this

const [stateMenu, setStateMenu] = useState(false);
  const translateY = new Animated.Value(0);

  useEffect(() => {
    controlMenu();
  }, [stateMenu]); // listen changes in state menu

  function controlMenu() {
    if (!stateMenu) {//fechar Menu
      //alert('Fechando');
      Animated.timing(translateY, {
        toValue: 0,
        duration: 400,  
        useNativeDriver: true,
        //delay: 300,
      }).start();
    }
    else {//abrir Menu
      //alert('Abrindo');
      Animated.timing(translateY, {
        toValue: 800,
        duration: 400,
        useNativeDriver: true,
        //delay: 300,
      }).start();
    }
  }
Related