From eb8b3bdd490e79b028126afdc038ce783b6186be Mon Sep 17 00:00:00 2001 From: Mike Fix Date: Thu, 7 Feb 2019 19:22:44 -0800 Subject: [PATCH] move online/offline listeners into tweet button --- components/Editor.js | 17 ++--------------- components/TweetButton.js | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/components/Editor.js b/components/Editor.js index e472e1c..016c238 100644 --- a/components/Editor.js +++ b/components/Editor.js @@ -45,7 +45,6 @@ class Editor extends React.Component { ...DEFAULT_SETTINGS, loading: true, code: props.content, - online: true, preset: DEFAULT_PRESET_ID } @@ -87,8 +86,7 @@ class Editor extends React.Component { ...getSettings(localStorage), // and then URL params ...initialState, - loading: false, - online: Boolean(window && window.navigator && window.navigator.onLine) + loading: false } // Makes sure the slash in 'application/X' is decoded @@ -98,27 +96,17 @@ class Editor extends React.Component { this.updateState(newState) - window.addEventListener('offline', this.setOffline) - window.addEventListener('online', this.setOnline) - this.isSafari = window.navigator && window.navigator.userAgent.indexOf('Safari') !== -1 && window.navigator.userAgent.indexOf('Chrome') === -1 } - componentWillUnmount() { - window.removeEventListener('offline', this.setOffline) - window.removeEventListener('online', this.setOnline) - } - updateState = updates => this.setState(updates, () => this.props.onUpdate(this.state)) updateCode = code => this.updateState({ code }) updateAspectRatio = aspectRatio => this.updateState({ aspectRatio }) updateTitleBar = titleBar => this.updateState({ titleBar }) - setOffline = () => this.updateState({ online: false }) - setOnline = () => this.updateState({ online: true }) async getCarbonImage( { @@ -293,7 +281,6 @@ class Editor extends React.Component { backgroundImage, backgroundMode, aspectRatio, - online, titleBar, code, exportSize @@ -348,7 +335,7 @@ class Editor extends React.Component { getCarbonImage={this.getCarbonImage} />
- {this.props.api.tweet && online && } + {this.props.api.tweet && } { + window.addEventListener(key, fn) + return () => window.removeEventListener(key, fn) + }, []) +} + function TweetButton(props) { + const [online, setOnline] = React.useState(true) const [onClick, { loading }] = useAsyncCallback(props.onClick) + + React.useEffect(() => { + setOnline(Boolean(window && window.navigator && window.navigator.onLine)) + }, []) + + useWindowListener('offline', () => setOnline(false)) + useWindowListener('online', () => setOnline(true)) + + if (!online) { + return null + } + return (