Home > database >  How to trigger a function once the animated value is over .8 and pass in the current state to that f
How to trigger a function once the animated value is over .8 and pass in the current state to that f

Time:11-12

I'm trying to trigger this function called moveNow() once reactAnimated value is over .8. I'm currently doing this with a addListner() and I'm adding a listener every time a list called DATA_LAYER.names in my useContext changes. The problem is that past listeners with old versions of DATA_LAYER.names are still getting triggerd when the value is over .8. Basically I wan't to go to the next screen when reactAnimated value is over .8 but I also only want to go to the other screen if the names list isn't empty. However, if I add a name and then delete and make reactAnimated value over .8 it still goes to the other screen, because the old listener when names had name is still there.

const DATA_LAYER = React.useContext(DataLayerContext);
const reactAnimated = React.useRef(new Animated.Value(0)).current;
/*
  Some simple functions to move the reactAnimated value
*/
const moveNow = () =>{
    if (DATA_LAYER.names.length!==0){
      props.navigation.navigate("loadingscreen");
    }
}


React.useEffect(()=>{
    // Animated values
    reactAnimated.addListener(val=>{
       if (val["value"]>.8){
          moveNow() // move to next page
       }
    });


  },[DATA_LAYER.names])

CodePudding user response:

You can cleanup the listener in the useEffect return function.

React.useEffect(()=>{
    // Animated values
    reactAnimated.addListener(val=>{
       if (val["value"]>.8){
          moveNow() // move to next page
       }
    });

   return () => reactAnimated.removeAllListeners()
  },[DATA_LAYER.names])
  • Related