RIP21 / react-simplemde-editor

React wrapper for simplemde (easymde) markdown editor

Home Page:https://react-simplemde-edtior.netlify.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Event handlers are only installed once but never updated

Johennes opened this issue · comments

While investigating mattermost/focalboard#292 and mattermost/focalboard#356 we uncovered that all the editor events are only installed once in componentDidMount. When the props change, those initially installed handlers are not removed / updated.

Since the event handlers are part of the component's props, I believe they should be updated in componentDidUpdate to prevent triggering stale handlers.

Here is a sub-optimal naive implementation that I used to verify the root cause:

diff --git a/src/index.tsx b/src/index.tsx
index 3930b3b..4213cc0 100755
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -86,18 +86,40 @@ export default class SimpleMDEEditor extends React.PureComponent<
   componentDidUpdate(prevProps: SimpleMDEEditorProps) {
     if (
       !this.keyChange &&
       this.props.value !== this.state.value && // This is somehow fixes moving cursor for controlled case
       this.props.value !== prevProps.value // This one fixes no value change for uncontrolled input. If it's uncontrolled prevProps will be the same
     ) {
       this.simpleMde!.value(this.props.value || "");
     }
     this.keyChange = false;
+
+    prevProps.events &&
+      Object.entries(prevProps.events).forEach(([eventName, callback]) => {
+        if (eventName && callback) {
+          this.simpleMde &&
+            this.simpleMde.codemirror.off(
+              eventName as DOMEvent,
+              callback as any
+            );
+        }
+      });
+
+    this.props.events &&
+      Object.entries(this.props.events).forEach(([eventName, callback]) => {
+        if (eventName && callback) {
+          this.simpleMde &&
+            this.simpleMde.codemirror.on(
+              eventName as DOMEvent,
+              callback as any
+            );
+        }
+      });
   }
 
   componentWillUnmount() {

Feel free to open PR to fix that. I'm honestly, don't have time for any of the changes :(
I want to refactor it to use hooks etc. but it's just so low priority for me, so I don't know when I'll do that.

@Johennes I rewrote everything completely, please check v5.0.0 it should be WAY better and more reactive as it uses hooks.
Let me know how it looks now.
And, yeah, there are some breaking changes, so please check them in changelog/releases.
Feel free to check upgraded docs too.

Nice! Thanks a lot. I logged mattermost/focalboard#396 to try out and update the dependency in Focalboard.

@Johennes nice this shitty wrapper I wrote is actually used in such a nice project :D Flattered :D My rewrite was for good then! :)