Skip to content

Commit db8f64b

Browse files
LewisYearsleyLewis Yearsley
and
Lewis Yearsley
authored
fix: cleanup native SVG animations (#232)
Co-authored-by: Lewis Yearsley <[email protected]>
1 parent fb0e704 commit db8f64b

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/native/Svg.tsx

+7-1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ class NativeSvg extends Component<IContentLoaderProps> {
3232

3333
idGradient = `${this.fixedId}-animated-diff`
3434

35+
unmounted = false
36+
3537
setAnimation = () => {
3638
// props.speed is in seconds as it is compatible with web
3739
// convert to milliseconds
@@ -44,7 +46,7 @@ class NativeSvg extends Component<IContentLoaderProps> {
4446
duration: durMs,
4547
useNativeDriver: true,
4648
}).start(() => {
47-
if (this.props.animate) {
49+
if (!this.unmounted && this.props.animate) {
4850
this.animatedValue.setValue(-1)
4951
this.setAnimation()
5052
}
@@ -63,6 +65,10 @@ class NativeSvg extends Component<IContentLoaderProps> {
6365
}
6466
}
6567

68+
componentWillUnmount() {
69+
this.unmounted = true
70+
}
71+
6672
render() {
6773
const {
6874
children,

src/native/__tests__/ContentLoader.test.tsx

+27
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as React from 'react'
2+
import { Animated } from 'react-native'
23
import * as renderer from 'react-test-renderer'
34
import * as ShallowRenderer from 'react-test-renderer/shallow'
45

@@ -121,4 +122,30 @@ describe('ContentLoader', () => {
121122
expect(propsFromFullField.rtl).toBe(true)
122123
})
123124
})
125+
126+
describe('when using SVG', () => {
127+
describe('cleanup', () => {
128+
afterAll(() => {
129+
jest.useRealTimers()
130+
})
131+
132+
it('cleans up animations when unmounted', () => {
133+
jest.useFakeTimers()
134+
const animationSpy = jest.spyOn(Animated, 'timing')
135+
136+
const mockSpeed = 10
137+
const { unmount } = renderer.create(
138+
<ContentLoader animate={true} height={200} speed={mockSpeed}>
139+
<Rect />
140+
</ContentLoader>
141+
)
142+
143+
jest.runTimersToTime(mockSpeed)
144+
unmount()
145+
jest.runTimersToTime(mockSpeed)
146+
147+
expect(animationSpy).toHaveBeenCalledTimes(1)
148+
})
149+
})
150+
})
124151
})

0 commit comments

Comments
 (0)