React native: error with animated value on progress bar

Viewed 25

In my react native app I want to have a progressbar animated values, problem is when component is mounted the bar is full already (View with backgroundColor RED is visible) even though progressValue is 0 according to my console logs... if I execute onStart nothing moves since it appears like animation already finished...

Is it because I'm using translate wrongly? How can I achieve correct animated effect?

const width = Math.round(Dimensions.get('window').width)-30;

    const progressValue = new Animated.Value(0);
    //const animation = null;

    const onStart = (duration ) => 
    {
        console.log(duration,width);
        const animation = Animated.timing(progressValue, {
            duration: duration,
            toValue: width,
            easing: Easing.linear,
            useNativeDriver: true,
        }).start(); 
    };

<View style={{width: width, height: 4,backgroundColor: 'white'}}>
                    <Animated.View style={{width: width, height: 4, backgroundColor: 'red', transform: [{translateX: progressValue}]}} />
                </View>
1 Answers

two things which i can see, always useRef for animation values

const width = Math.round(Dimensions.get('window').width)-30;

    const progressValue = useRef(new Animated.Value(0)).current; // add this
    //const animation = null;

    const onStart = useCallback((duration ) => 
    {
        console.log(duration,width);
        const animation = Animated.timing(progressValue, {
            duration: duration,
            toValue: width,
            easing: Easing.linear,
            useNativeDriver: true,
        }).start(); 
    },[progressValue]);

<View style={{width: width, height: 4,backgroundColor: 'white'}}>
                    <Animated.View style={{width: width, height: 4, backgroundColor: 'red', transform: [{translateX: progressValue}]}} />
                </View>

Also im hoping youre calling onStart in a useEffect like this

useEffect(() => {
onStart()
},[onStart])

Hope it helps. feel free for doubts

Related