Last active
March 14, 2018 09:29
-
-
Save torgeir/15b917e5097da06426d1313439f4c48e to your computer and use it in GitHub Desktop.
Js lazy fetch with getter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const wait = s => new Promise((resolve) => setTimeout(resolve, s * 1000)) | |
const state = {}; | |
dataField(state, "ip", "http://ip.jsontest.com/"); | |
console.log(state.ip); | |
wait(2) | |
.then(() => state.ip) | |
.then(console.log); | |
// {pending: true, value: null, error: null} | |
// .. | |
// {pending: false, value: "185.36.49.253", error: null} | |
function dataField (state, field, url) { | |
const data = { | |
pending: false, | |
value: null, | |
error: null, | |
}; | |
Object.defineProperty(state, field, { | |
get() { | |
if (data.value == null && !data.pending) { | |
data.pending = true; | |
fetch(url) | |
.then(res => res.json()) | |
.then(res => res.ip) | |
.then(ip => { | |
data.value = ip; | |
data.pending = false; | |
}) | |
.catch(error => data.error = error); | |
} | |
return data; | |
} | |
}); | |
}; | |
// {pending: true, value: null, error: null} | |
// .. | |
// {pending: false, value: "185.36.49.253", error: null} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment