Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@torgeir
Last active March 14, 2018 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torgeir/15b917e5097da06426d1313439f4c48e to your computer and use it in GitHub Desktop.
Save torgeir/15b917e5097da06426d1313439f4c48e to your computer and use it in GitHub Desktop.
Js lazy fetch with getter
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