3

I'm writing a single page application using mithril. The page loads some data from the server using m.request() in the oninit of the main component:

var root = document.getElementById("main");
var Data = {
        fetch: function () {
            m.request({
                method: "GET",
                url: "/api/read"
            })
                .then(function (items) {
                    // init models with data
                });
    }
}

var Home = {
    oninit: Data.fetch,
    view: function (vnode) {
        return m("div", [components]);
    }
}

m.route(root,
    "/",
    {
        "/": Home
    });

The data is a huge json, the page is to help edit the json by ensuring that certain foreign key constraints are met, and visualising it a bit better. Everything works as expected until a call a component that actually adds a brand new entry to any of the json objects i have. At this stage the page reloads, and the data gets fetched again, so I lose all the changes. It only ever happens once though and only on this call:

jsonModel[propertyName].push(JSON.parse(newObject))

After this first redraw I can modify the page as much as I like, this issue will not happen again. I can even refresh without it occurring.

Am I doing something fundamentally wrong in my structure? Can this refresh be prevented?

RekaB
  • 438
  • 5
  • 14
  • Without seeing more code it's tricky to know for sure.I'd recommend doing initial data fetches like that outside of a component entirely and having it return the promise. Then any later methods that need access to that data can call `.then()` on the promise and be assured that the data is loaded before they try to operate on it. – Tivac May 03 '18 at 23:14
  • It's difficult to tell what the problem might be from this snapshot. You could certainly get a lot of qualified help if you put the question to the Mithril chatroom: https://gitter.im/mithriljs/mithril.js – Barney May 03 '18 at 23:43

2 Answers2

2

It sounds like you want to call event.preventDefault() in the onclick handler for the <button> then, to prevent it from auto-submitting the form.

There's a few other approaches you could take, but that'll be the simplest.

Tivac
  • 2,553
  • 18
  • 21
0

I have found the issue but the actual error was not included in the question: the component firing the action is a button. This button was placed in a form tag and for some reason only triggered a submit once. Here's the code that would reproduce the issue.

Interestingly, when trying it in Edge it almost always refreshes. I would still be interested in why it only does it once on Chrome if anyone knows?

RekaB
  • 438
  • 5
  • 14