Skip to content

Commit 955d8c2

Browse files
committed
✨ create useEffectWithComparison hook
1 parent 5da8b24 commit 955d8c2

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

client/modules/IDE/pages/MobileIDEView.jsx

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,44 @@ const getNatOptions = (username = undefined) =>
6666
]
6767
);
6868

69+
70+
const asd = (props, prevProps) => {
71+
if (isUserOwner(this.props) && this.props.project.id) {
72+
if (
73+
props.preferences.autosave &&
74+
props.ide.unsavedChanges &&
75+
!props.ide.justOpenedProject
76+
) {
77+
if (
78+
props.selectedFile.name === prevProps.selectedFile.name &&
79+
props.selectedFile.content !== prevProps.selectedFile.content
80+
) {
81+
if (this.autosaveInterval) {
82+
clearTimeout(this.autosaveInterval);
83+
}
84+
console.log('will save project in 20 seconds');
85+
this.autosaveInterval = setTimeout(props.autosaveProject, 20000);
86+
}
87+
} else if (this.autosaveInterval && !props.preferences.autosave) {
88+
clearTimeout(this.autosaveInterval);
89+
this.autosaveInterval = null;
90+
}
91+
} else if (this.autosaveInterval) {
92+
clearTimeout(this.autosaveInterval);
93+
this.autosaveInterval = null;
94+
}
95+
};
96+
97+
const useEffectWithComparison = (fn, props) => {
98+
const [prevProps, update] = useState({});
99+
100+
return useEffect(() => {
101+
fn(props, prevProps);
102+
update(props);
103+
}, Object.values(props));
104+
};
105+
106+
69107
const MobileIDEView = (props) => {
70108
const {
71109
ide, project, selectedFile, user, params, unsavedChanges, collapseConsole,
@@ -103,6 +141,9 @@ const MobileIDEView = (props) => {
103141
}, [params, project, username]);
104142

105143

144+
// useEffectWithComparison(() => alert('haha'), { consoleIsExpanded });
145+
146+
106147
return (
107148
<Screen fullscreen>
108149
<Header

client/utils/custom-hooks.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,15 @@ export const useModalBehavior = (hideOverlay) => {
4040

4141
return [visible, trigger, setRef];
4242
};
43+
44+
// Usage: useEffectWithComparison((props, prevProps) => { ... }, { prop1, prop2 })
45+
// This hook basically applies useEffect but keeping track of the last value of relevant props
46+
// So you can passa a 2-param function to capture new and old values and do whatever with them.
47+
const useEffectWithComparison = (fn, props) => {
48+
const [prevProps, update] = useState({});
49+
50+
return useEffect(() => {
51+
fn(props, prevProps);
52+
update(props);
53+
}, Object.values(props));
54+
};

0 commit comments

Comments
 (0)