- I have a function that makes a fetch call to a particular site for data.
- Then, I must filter that data based on the parameter passed in the function.
- I must return the match or matches from this array of data.
- Save the output of the function to a CONST, pass in the parameter, and log the result.
My code doing the above and returning
:
- When I
return
, I get undefined. - When I
console.log
I get the correctly filter objects.
Returning (not properly, returns undefined)
const fetchData = ({ name, num }) => {
const request = fetch(`apiLink`)
.then((res) => res.json())
.then(data => {
// If the name parameter was passed, filter for it
if (name) {
return (data.filter(person => person.name.includes(name)));
}
})
.catch(() => {
console.error('oh no');
})
}
const res = fetchData({
name: 'Tina',
});
console.log(res); // undefined via return
Console logging the result actually shows the filter data
const fetchData = ({ name, num }) => {
const request = fetch(`apiLink`)
.then((res) => res.json())
.then(data => {
// If the name parameter was passed, filter for it
if (name) {
console.log((data.filter(person => person.name.includes(name)));
}
})
.catch(() => {
console.error('oh no');
})
}
const res = fetchData({
name: 'Tina',
});
console.log(res);
Can anyone help me understand why it is returning undefined? And how I can return and filter properly (after the data is fetched)?
Thank you so much!