dispatch inside focusChangeEffect throws exception

Hello I’m new to using codemirror.

I was following this thread to format my code using the same dispatch approach, but I want that to happen after the user removes focus from code editor. However, no matter what I do, I keep getting this exception RangeError: Trying to update state with a transaction that doesn’t start from the previous state. I tried to do it via a transaction and assigning startState of the transaction to the state passed from focusChangeEffect and same exception.

Here is minimal setup to reproduce the error

Is this a bug or am I doing something wrong?

You definitely shouldn’t produce any side effects from forChangeEffect functions, no. It should create effects, and nothing more. Use update listeners is you want to respond to focus changes with side effects.

Ok I figured it might be an issue of side effects in the wrong place.

I went through the docs and couldn’t figure out which functions to use instead, do you have any examples any where for listening to a blur event on the editor?

Thank you.

An update listener can check update.focusChanged and/or update.view.hasFocus to figure out when the view is blurred.

Thank you, it works perfectly now.

For anyone in the future the code looks something like this:

const onBlurExt = EditorView.updateListener.of((update) => {
        if (update.focusChanged) {
            if (update.view.hasFocus === false) {
                let transaction = view.state.update({
                    changes: {
                        from: 0, 
                        to: view.state.doc.length,
                        insert: `some change`

and then add to your EditorView extensions. I can’t say I completely understand how to use Facets as I had to search around the forums for syntax.