Skip to content

Commit

Permalink
fix: cleanup native SVG animations (#232)
Browse files Browse the repository at this point in the history
Co-authored-by: Lewis Yearsley <[email protected]>
  • Loading branch information
LewisYearsley and Lewis Yearsley authored Mar 4, 2021
1 parent fb0e704 commit db8f64b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/native/Svg.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class NativeSvg extends Component<IContentLoaderProps> {

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

unmounted = false

setAnimation = () => {
// props.speed is in seconds as it is compatible with web
// convert to milliseconds
Expand All @@ -44,7 +46,7 @@ class NativeSvg extends Component<IContentLoaderProps> {
duration: durMs,
useNativeDriver: true,
}).start(() => {
if (this.props.animate) {
if (!this.unmounted && this.props.animate) {
this.animatedValue.setValue(-1)
this.setAnimation()
}
Expand All @@ -63,6 +65,10 @@ class NativeSvg extends Component<IContentLoaderProps> {
}
}

componentWillUnmount() {
this.unmounted = true
}

render() {
const {
children,
Expand Down
27 changes: 27 additions & 0 deletions src/native/__tests__/ContentLoader.test.tsx
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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(
<ContentLoader animate={true} height={200} speed={mockSpeed}>
<Rect />
</ContentLoader>
)

jest.runTimersToTime(mockSpeed)
unmount()
jest.runTimersToTime(mockSpeed)

expect(animationSpy).toHaveBeenCalledTimes(1)
})
})
})
})

0 comments on commit db8f64b

Please sign in to comment.