Search code examples
react-nativereact-animated

React-Native Animated does not work near setState


let animatedHeight = new Animated.Value(50);

const animate = () => {
    animatedHeight.setValue(50);
    Animated.timing(animatedHeight, {
      toValue: 0,
      duration: 200,
      useNativeDriver: true
    }).start();
  };



  const handleSubmit = async (values:ILoginProps) => {
        setLoading(true);

        axios.post('http://127.0.0.1:3333/api/v1/auth/login', values)
        .then(res => {
            console.log(res);
        })
        .catch(err => {
            console.log(err);
            animate();
            setLoading(false);
        })
    
  }

  <Animated.View style={[style.errorContainer, {transform: [{translateY: animatedHeight}]}]}>
     <Text style={style.errorText}>Credentials not found!</Text>
  </Animated.View>

I have this code, first I set a loading state and then execute a animate function which runs the Animated function to create the animation effect.

When i have setLoading(true) before animate(), the animation doesn't happen.

I really have no idea why this happens and no idea how to solve this


Solution

  • Use useRef hook to wrap your animated value. React will keep tracking of its value after re-rendering, in other case you might lose it.

    let animatedHeight = React.useRef(new Animated.Value(50)).current;