diff --git a/docs/mithril.request.md b/docs/mithril.request.md index d07ef0f0..491cb537 100644 --- a/docs/mithril.request.md +++ b/docs/mithril.request.md @@ -487,7 +487,7 @@ where: var demo = {} demo.controller = function() { - var users = m.request({method: "GET", url: "test.json", background: true, initialValue: []}) + var users = m.request({method: "GET", url: "/api/users", background: true, initialValue: []}) users.then(m.redraw) return {users: users} } @@ -503,7 +503,41 @@ where: ``` It's strongly recommended that you set an `initialValue` option in ALL requests if you set the `background` option to true. + + When calling multiple background AJAX requests, it's recommended that you use [`m.sync`](mithril.sync.md) to batch redraw once at the end of all requests, as opposed to repeatedly redrawing after every request: + ```javascript + var demo = {} + + demo.controller = function() { + var users = m.request({method: "GET", url: "/api/users", background: true, initialValue: []}) + var projects = m.request({method: "GET", url: "/api/projects", background: true, initialValue: []}) + + m.sync([users, projects]).then(m.redraw) + + return {users: users, projects: projects} + } + ``` + + Make sure to add null checks if your request value can be null + + ```javascript + var demo = {} + + demo.controller = function() { + var user = m.request({method: "GET", url: "/api/users/1", background: true, initialValue: null}) + user.then(m.redraw) + return {user: user} + } + + demo.view = function(ctrl) { + return m("div", [ + //in the first redraw, there's no user, so ensure we don't throw an error + ctrl.user ? ctrl.user.name : "no user" + ]) + } + ``` + - **any initialValue** (optional) The value that populates the returned getter-setter before the request completes. This is useful when using the `background` option, in order to avoid the need for null checks in views that may be attempting to access the returned getter-setter before the asynchronous request resolves.