From 6b7c741658abc38aa7edf109d999c7c8a3cfcb4f Mon Sep 17 00:00:00 2001 From: jomo Date: Thu, 11 Aug 2022 02:52:00 +0200 Subject: [PATCH] fetch items from server before locally checking available IDs --- static/form.js | 68 +++++++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 31 deletions(-) diff --git a/static/form.js b/static/form.js index 7ef51d9..4ae4968 100644 --- a/static/form.js +++ b/static/form.js @@ -3,13 +3,17 @@ const id = new URLSearchParams(window.location.search).get('id'); document.onreadystatechange = function() { if (document.readyState === 'interactive') { - fetch('/api/items').then(r => r.json()).then((data) => { - items = data; - fillForm(); - }); + fetchItems(fillForm); } } +function fetchItems(cb) { + fetch('/api/items').then(r => r.json()).then((data) => { + items = data; + cb(); + }); +} + function fillForm() { const item = items[id]; knownTypes(); @@ -77,39 +81,41 @@ function save() { hidden: document.getElementById('hidden').checked, } - if (item.id.includes('?')) { - let n = 1; - while (true) { - const candidate = item.id.replace('?', n++); - if (!Object.keys(items).includes(candidate)) { - item.id = candidate; - break; + fetchItems(() => { + if (item.id.includes('?')) { + let n = 1; + while (true) { + const candidate = item.id.replace('?', n++); + if (!Object.keys(items).includes(candidate)) { + item.id = candidate; + break; + } } } - } - if (items[item.id]) { - if (!id || (id && id != item.id)) { - alert(`ID ${item.id} exists. Please chose a different ID or edit the existing ${item.id} item!`); - return; + if (items[item.id]) { + if (!id || (id && id != item.id)) { + alert(`ID ${item.id} exists. Please chose a different ID or edit the existing ${item.id} item!`); + return; + } } - } - const original_id = id || item.id; + const original_id = id || item.id; - fetch(`/api/items/${original_id}`, { - method: 'PUT', - headers: {'Content-Type': 'application/json'}, - body: JSON.stringify(item), - }) - .then(r => { - if (r.ok) { - window.location.href = '../'; - } else { - r.text().then(t => alert(`Error:\n${t}`)); - } - }).catch(error => { - alert(`Error:\n${error}`); + fetch(`/api/items/${original_id}`, { + method: 'PUT', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify(item), + }) + .then(r => { + if (r.ok) { + window.location.href = '../'; + } else { + r.text().then(t => alert(`Error:\n${t}`)); + } + }).catch(error => { + alert(`Error:\n${error}`); + }); }); }