Last active
November 25, 2019 18:15
-
-
Save Blezzoh/b2aa2412abe833f8e61c89a88184239e to your computer and use it in GitHub Desktop.
worker to get the data
This file contains hidden or 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
export default () => { | |
// 'self' instead of 'window' | |
self.addEventListener("message", e => {// eslint-disable-line no-restricted-globals | |
// the above comment removes the eslint error for self | |
if (!e) return; | |
// the message passed is in e.data | |
// we are passing it a json {numberOfUsers: <number>} | |
var numberOfUsers = e.data.numberOfUsers; | |
// function to process the returned data | |
var userSelector = function(users) { | |
if (Array.isArray(users) && users.length) { | |
return users.map(function(d) { | |
return { | |
name: `${d.name.title} ${d.name.first} ${d.name.last}`, | |
address: `${d.location.street.number} ${d.location.street.name}, | |
${d.location.city}, ${d.location.state} ${d.location.postcode}`, | |
phone: d.phone, | |
age: d.dob.age | |
}; | |
}); | |
} | |
return []; | |
}; | |
// fetching the <numberOfUsers> users | |
fetch("https://randomuser.me/api/?results=" + numberOfUsers, { | |
headers: { | |
"Content-Type": "application/json" | |
} | |
}).then(resp => resp.json()) | |
.then(data => { | |
postMessage(userSelector(data.results)); | |
}) | |
.catch(err => { | |
// any way you want to handle errors | |
postMessage([]); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment