Moshe M
Moshe M

Reputation: 91

Processing an Object During Fetch Returns 'undefined'

I'm fetching an API of dogs, it returns an object. I want to make changes in the object before I convert it to an array and setState() it. Problem is it returns 'undefined'. I assume the function is ok because it does work if I run in outside the fetch, or maybe I'm missing something here?

componentDidMount() {
    fetch("https://dog.ceo/api/breeds/list/all")
      (res => res.json())
      .then(res => res.message)
      .then(res => this.processReq(res)) // <--- undefined
      .then(res => Object.entries(res))
      .then(res => this.setState({ allBreeds: res }));
  }

  processReq = breed =>
    Object.keys(breed).forEach(key => {
      if (key === "australian") {
        breed["shepherd"] = [key];
        delete breed[key];
      } else if (key === "germanshepherd") {
        breed["shepherd"].push("german");
        delete breed[key];
      }
    });

Is there a way to manipulate the object during the fetch? Or maybe it would be easier to setState() it as an array and then process it?

Upvotes: 0

Views: 171

Answers (2)

Muhammad Ali
Muhammad Ali

Reputation: 2648

Actually forEach function doesn't return anything so that's why it's giving undefined, you should change it to:

processReq = breed => {
    Object.keys(breed).forEach(key => {
      if (key === "australian") {
        breed["shepherd"] = [key];
        delete breed[key];
      } else if (key === "germanshepherd") {
        breed["shepherd"].push("german");
        delete breed[key];
      }
    });
    return breed;
}

Upvotes: 2

Duncan Thacker
Duncan Thacker

Reputation: 5188

The processReq function doesn't have a return statement, so it just returns undefined. Just put a return breed; on the end of it and you'll be fine.

Upvotes: 0

Related Questions