Me gustaría cambiar un valor cuando finaliza una función fadeOut.
tengo la siguiente función:
const fadeOut = (duration: number = 300) => { Animated.timing( opacity, { toValue: 0, duration, useNativeDriver: true } ).start(); }Y lo llamo así:
const fadeOutScreen = () => { fadeOut(1000); // The value would be true when the fadeOut is over setHide(true); }Pero el valor se cambia antes de que finalice la operación.
¿Como puedo resolver esto?
Hazlo asíncrono:
Aquí están los documentos
const fadeOut = (duration: number = 300) => new Promise<boolean>(resolve => { Animated.timing( opacity, { toValue: 0, duration, useNativeDriver: true, } ).start(({finished}) => resolve(finished)); }); const fadeOutScreen = async () => { const finished = await fadeOut(1000); if (finished) setHide(true); else { // animation was interrupted } };La animación se ejecuta de forma asincrónica, pero la función fadeOutScreen continuará ejecutándose de forma sincrónica después de que se inicie la animación.
Animated.start() , sin embargo, toma una devolución de llamada que se llama una vez que finaliza la animación, por lo que puede hacerlo así:
const fadeOut = (duration: number = 300, cb?: (boolean) => void) => { Animated.timing( opacity, { toValue: 0, duration, useNativeDriver: true } ).start( //vvvvvvvv--- This tells whether the animation has finished or stopped ({finished}) => cb?.(finished) // ^^--- Only call callback if present (new syntax) ); } const fadeOutScreen = () => { fadeOut( 1000, finished => { if(finished) setHide(true); } ); }