I've got a function that makes a call to my Node backend, and retrieves an array of objects. This function, named queryDatabase, listed below:
function queryDatabase(locationName, timeFrame) {
const location = locationName.charAt(0).toUpperCase() + locationName.slice(1);
return new Promise((resolve) => {
Axios.get(`/api/measurements/${location}/${timeFrame}`)
.then((resp) => {
console.log('RESPONSE', resp);
resolve(resp.data);
});
});
}
This function is called by yet another function, getAllGroupNames, that retrieves an object and gets all group names out of it. This function returns a promise, with an array of the list of group names that my front-end needs to render.
export default function (locationName) {
const arrayOfGroupNames = [];
return new Promise((resolve) => {
queryDatabase('Pagodedreef', 'uur').then((data) => {
data.forEach((measurement) => {
measurement.groups.forEach((group) => {
if (!arrayOfGroupNames.includes(group.name)) {
arrayOfGroupNames.push(group.name);
}
});
});
resolve(arrayOfGroupNames);
});
});
}
I feel the above code is correct. The problem, however, arises when a function in my front-end React code, calls getAllGroupNames and tries to iterate over the array to return a new Checkbox element for each value.
renderCheckboxes() {
getAllGroupNames('Pagodedreef').then((array) => {
return array.map((groupName, index) => (
<div className="checkboxes" key={index.toString()}>
<label htmlFor={groupName}>
<input
type="checkbox"
id={groupName}
value={groupName}
onChange={this.onCheckboxChange}
checked={this.props.selectedGroups.includes(groupName)}
/>
{groupName}
</label>
</div>
));
});
}
If I put a console.log()
around the getAllGroupNames().then()
function, it returns an unresolved promise. I can't figure out how I can, instead of returning a promise, return the elements that need to be rendered.
If I chain an additional .then()
at the end of the previous then()
and log the value of that - it lists the values that I do indeed need. But again, when I return those - it has no effect.
Thank you in advance for helping me.