Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.