So I made this little fetch function in a React project to loop through the returned object and give me a number of something.
I'm trying to get back the value of profileCount to access it outside of the async function.
How would I do that?
useEffect(() => {
async function getProfiles() {
try {
const url = '';
let h = new Headers();
h.append('Accept', 'application/json');
let encoded = window.btoa('superuser:superuser');
let auth = 'Basic ' + encoded;
h.append('Authorization', auth);
const response = await fetch(url, {
method: 'GET',
mode: 'cors',
headers: h,
credentials: 'same-origin',
});
const data = await response.json();
let results = data.results;
let profileCount = 0;
for (let key in results) {
let innerObject = results[key];
for (let newKey in innerObject) {
if (innerObject[newKey].indexOf('pages/ProfilePage') > -1) {
profileCount += 1;
return profileCount;
}
}
}
} catch (err) {
console.log('test' + err);
}
}
getProfiles();
}, []);
Your code is good, just relocate the return statement after the for.
for (let key in results) {
let innerObject = results[key];
for (let newKey in innerObject) {
if (innerObject[newKey].indexOf('pages/ProfilePage') > -1) {
profileCount += 1;
}
}
}
return profileCount;
The workflow is the following,
useEffect(async () => {
async function getProfiles() {}
const count = await getProfiles();
}, []);
But you might have to do this to avoid warning,
useEffect(() => {
(async () => {
let response = await fetch('api/data')
})();
}, [])