Creating Plugin that make request to backend

Hello, I’m trying to develop a Plugin that make request to backend with serialized steps when doc changed. I dont know if my approach is correct or it could be better to use another class instead of create a Plugin.

It could be the “Plugin”

let http = this.http
const httpPlugin = new Plugin({
    state: {
        init() {
            console.log(http)
            return http
        },
        apply(tr, http) {
            if (tr.docChanged) {
                console.log('Doc changed...')
                //TODO serialize steps and send to back with http
            }
            return http
        }
    }

})

1 Like

Hi @thejosess and welcome

I would keep the asynchronous HTTP calls out of your plugins. Instead, use dispatchTransaction to get any updates from the editor you need. When such an update comes, you can send the document (or changes) to the server.

If you need to apply a change to the document as a result of such an HTTP call, you would create a new Transaction and dispatch that to the view. The collab demo on the website is an example of this.

Kindly Frederik

2 Likes

Thank you, I will try like this.

@thejosess I think http calls in plugins is perfectly fine, but should be done in the “view” section. Doing it in the state section is problematic as it creates uncontrolled side effects. Instead, you could collect steps you need in plugin state and then “flush” those steps to the service when the doc changes with some sort of throttle/debounce.

We think about the state methods like redux reducers while the “view” section is for side effects (like http calls, setting up global listeners, etc.).