Skip to content

Commit 8dcecdd

Browse files
committed
Workaround of componentWillUnmount
1 parent ebdd952 commit 8dcecdd

File tree

2 files changed

+30
-12
lines changed

2 files changed

+30
-12
lines changed

src/components/Main.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const Main = props => {
1515
{isBrowser && (
1616
<>
1717
<div className='animation saron' id='container' />
18-
{props.playing && <Visualizer player={props.player} />}
18+
<Visualizer player={props.player} playing={props.playing} />
1919
<details>
2020
<summary>Keyboard Controls</summary>
2121
<dl>

src/components/Visualizer.js

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import React from 'react';
22
import PropTypes from 'prop-types';
33

4+
const DELAY = 500;
5+
46
export default class Visualizer extends React.PureComponent {
57
rafId = null;
68
timerId = null;
@@ -17,17 +19,26 @@ export default class Visualizer extends React.PureComponent {
1719
};
1820
}
1921

20-
componentDidMount() {
21-
this.initiateEQ();
22-
this.createVisualizer();
23-
this.startDrawing();
24-
}
2522

26-
componentWillUnmount() {
27-
this.stopDrawing();
28-
this.state.eq.analyser.disconnect();
29-
this.state.eq.src.disconnect();
30-
this.state.eq.context.close();
23+
// In order to get around some mobile browser limitations,
24+
// we can only generate a lot
25+
// of the audio context stuff AFTER the audio has been triggered.
26+
// We can't see it until
27+
// then anyway so it makes no difference to desktop.
28+
componentDidUpdate(prevProps) {
29+
if (prevProps.playing !== this.props.playing) {
30+
if (this.props.playing) {
31+
this.initiateEQ();
32+
this.createVisualizer();
33+
this.startDrawing();
34+
} else {
35+
// Workaround of componentWillUnmount to delay the clean up and achieve fadeout animation
36+
setTimeout(() => {
37+
this.stopDrawing();
38+
this.reset();
39+
}, DELAY)
40+
}
41+
}
3142
}
3243

3344
initiateEQ() {
@@ -53,6 +64,12 @@ export default class Visualizer extends React.PureComponent {
5364
this.setState({ eq });
5465
}
5566

67+
reset = () => {
68+
this.rafId = null;
69+
this.state.eq.analyser.disconnect();
70+
this.state.eq.src.disconnect();
71+
}
72+
5673
/** *
5774
* The equalizer bands available need to be updated
5875
* constantly in order to ensure that the value for any
@@ -161,5 +178,6 @@ export default class Visualizer extends React.PureComponent {
161178
}
162179

163180
Visualizer.propTypes = {
164-
player: PropTypes.object
181+
player: PropTypes.object,
182+
playing: PropTypes.bool
165183
};

0 commit comments

Comments
 (0)