From db8f64b57f529a194100c32a392f14c80b0b253c Mon Sep 17 00:00:00 2001 From: Lewis Yearsley Date: Thu, 4 Mar 2021 11:57:49 +0000 Subject: [PATCH] fix: cleanup native SVG animations (#232) Co-authored-by: Lewis Yearsley --- src/native/Svg.tsx | 8 +++++- src/native/__tests__/ContentLoader.test.tsx | 27 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/native/Svg.tsx b/src/native/Svg.tsx index db7932cc..f1c2595e 100644 --- a/src/native/Svg.tsx +++ b/src/native/Svg.tsx @@ -32,6 +32,8 @@ class NativeSvg extends Component { idGradient = `${this.fixedId}-animated-diff` + unmounted = false + setAnimation = () => { // props.speed is in seconds as it is compatible with web // convert to milliseconds @@ -44,7 +46,7 @@ class NativeSvg extends Component { duration: durMs, useNativeDriver: true, }).start(() => { - if (this.props.animate) { + if (!this.unmounted && this.props.animate) { this.animatedValue.setValue(-1) this.setAnimation() } @@ -63,6 +65,10 @@ class NativeSvg extends Component { } } + componentWillUnmount() { + this.unmounted = true + } + render() { const { children, diff --git a/src/native/__tests__/ContentLoader.test.tsx b/src/native/__tests__/ContentLoader.test.tsx index b301bc53..66b840c1 100644 --- a/src/native/__tests__/ContentLoader.test.tsx +++ b/src/native/__tests__/ContentLoader.test.tsx @@ -1,4 +1,5 @@ import * as React from 'react' +import { Animated } from 'react-native' import * as renderer from 'react-test-renderer' import * as ShallowRenderer from 'react-test-renderer/shallow' @@ -121,4 +122,30 @@ describe('ContentLoader', () => { expect(propsFromFullField.rtl).toBe(true) }) }) + + describe('when using SVG', () => { + describe('cleanup', () => { + afterAll(() => { + jest.useRealTimers() + }) + + it('cleans up animations when unmounted', () => { + jest.useFakeTimers() + const animationSpy = jest.spyOn(Animated, 'timing') + + const mockSpeed = 10 + const { unmount } = renderer.create( + + + + ) + + jest.runTimersToTime(mockSpeed) + unmount() + jest.runTimersToTime(mockSpeed) + + expect(animationSpy).toHaveBeenCalledTimes(1) + }) + }) + }) })