0
  1. I have a function that makes a fetch call to a particular site for data.
  2. Then, I must filter that data based on the parameter passed in the function.
  3. I must return the match or matches from this array of data.
  4. 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!

wolfie777
  • 43
  • 8
  • 1
    Use async/await or resolve the promise. – Invizi Sep 04 '21 at 13:17
  • I have to only use ES6 :/ – wolfie777 Sep 04 '21 at 13:31
  • @wolfie777 Then return the Promise, and `then()` it where you need the value. – Ivar Sep 04 '21 at 13:42
  • I thought that's what I was doing! any pointers to help me out? I thought I was returning the filtered data after the promise since it is 2 .thens deep. – wolfie777 Sep 04 '21 at 13:45
  • You're not returning anything from your `fetchData()` function. The `return` applies to the surrounding function which is the callback arrow function `data => { ... }`. You're only returning from your `then` callback. You'll need to return the `request` variable from your `fetchData()` function and then use `.then()` on the returned promise. Like `fetchData({ name: 'Tina' }).then(data => console.log(data));` – Ivar Sep 04 '21 at 13:52
  • I am doing just as you suggested by chaining the .then `fetchData({ name: 'Tina' }).then(data => console.log(data));` but when I return the data (not console.log it), it still says undefined. `fetchData({ name: 'Tina' }).then(data => data);` – wolfie777 Sep 04 '21 at 22:48

0 Answers0