From 955d8c20a46bc066c32a3042717c027679c5a34b Mon Sep 17 00:00:00 2001 From: ghalestrilo Date: Thu, 13 Aug 2020 17:02:39 -0300 Subject: [PATCH] :sparkles: create useEffectWithComparison hook --- client/modules/IDE/pages/MobileIDEView.jsx | 41 ++++++++++++++++++++++ client/utils/custom-hooks.js | 12 +++++++ 2 files changed, 53 insertions(+) diff --git a/client/modules/IDE/pages/MobileIDEView.jsx b/client/modules/IDE/pages/MobileIDEView.jsx index eb0f6031..e62d63b4 100644 --- a/client/modules/IDE/pages/MobileIDEView.jsx +++ b/client/modules/IDE/pages/MobileIDEView.jsx @@ -66,6 +66,44 @@ const getNatOptions = (username = undefined) => ] ); + +const asd = (props, prevProps) => { + if (isUserOwner(this.props) && this.props.project.id) { + if ( + props.preferences.autosave && + props.ide.unsavedChanges && + !props.ide.justOpenedProject + ) { + if ( + props.selectedFile.name === prevProps.selectedFile.name && + props.selectedFile.content !== prevProps.selectedFile.content + ) { + if (this.autosaveInterval) { + clearTimeout(this.autosaveInterval); + } + console.log('will save project in 20 seconds'); + this.autosaveInterval = setTimeout(props.autosaveProject, 20000); + } + } else if (this.autosaveInterval && !props.preferences.autosave) { + clearTimeout(this.autosaveInterval); + this.autosaveInterval = null; + } + } else if (this.autosaveInterval) { + clearTimeout(this.autosaveInterval); + this.autosaveInterval = null; + } +}; + +const useEffectWithComparison = (fn, props) => { + const [prevProps, update] = useState({}); + + return useEffect(() => { + fn(props, prevProps); + update(props); + }, Object.values(props)); +}; + + const MobileIDEView = (props) => { const { ide, project, selectedFile, user, params, unsavedChanges, collapseConsole, @@ -103,6 +141,9 @@ const MobileIDEView = (props) => { }, [params, project, username]); + // useEffectWithComparison(() => alert('haha'), { consoleIsExpanded }); + + return (
{ return [visible, trigger, setRef]; }; + +// Usage: useEffectWithComparison((props, prevProps) => { ... }, { prop1, prop2 }) +// This hook basically applies useEffect but keeping track of the last value of relevant props +// So you can passa a 2-param function to capture new and old values and do whatever with them. +const useEffectWithComparison = (fn, props) => { + const [prevProps, update] = useState({}); + + return useEffect(() => { + fn(props, prevProps); + update(props); + }, Object.values(props)); +};