xObject sometimes not updated when using REST API

Hi!

I’m loading JavaScript into an XWiki page which modifies an XObject and saves it when the page is saved. The save call gets an HTTP 202 status. Sometimes the XObject is not actually updated. The server logs no error.

My code looks something like this:

require(["xwiki-meta"], (xwikiMeta) => {
    // load XObject, render custom widget, update the XObject properties based on user input
    document.observe("xwiki:actions:beforeSave", async () => {
        await fetch(`${xwikiMeta.restURL}/objects/Integrations.Code.FunctionalityClass/${xObject.number}?media=json`,
            {
                method: "PUT",
                headers: { "content-type": "application/json" },
                body: JSON.stringify(xObject),
            }
        )
    })
}

The XObject I save is not the main page object. That one is saved by the usual form submit.

What could be the reason it only sometimes works? Does my code make sense or am I doing something wrong?

Thanks!
Yves

Check the page history. My guess is that sometimes the changes made by your REST call are overwritten by the page save. And that happens because they are sent almost at the same time, and the standard save loads the doc from the database before the REST call finishes the update. It’s a classic concurrency issue.

That seemed to be the case. I was assuming my use of ‘await’ would take care of it. I guess the HTTP 202 means that the backend has not applied the change yet when the next call comes in.

When saving my XObject afterwards (“xwiki:document:saved”) it seems to work consistently.