sgerbhctim
sgerbhctim

Reputation: 3640

react .map not allowing me to iterate over object

Here is the component I am building. I have a dummy backend API that contains a list of fruits, and the response data looks as such:

{
  "data": {
    "1": {
      "apple": "Delicious"
    },
    "2": {
      "orange": "It's orange."
    }
  },
  "message": "success retrieved fruits list",
  "status": 200
}

Now I am building a component that calls my API (successfully) and I am trying to create a list of the items within data.

class FruitList extends Component {

    constructor(props) {
        super(props);
        this.state = {
            fruits: {},
            error: null
        }
    }

    componentDidMount() {
        fruitsApi.getFruits()
            .then(response => response.json())
            .then(
                (results) => {
                    this.setState({
                        fruits: results.data,
                        error: false
                    });
                },
                (error) => {
                    this.setState({ error: true });
                    console.log(error);
                }
            )
    }

    getFruits() {
        const items = this.state.fruits.map(
            ([k, v]) => <li key={k}>{v}</li>
        );
    }

    render() {
        return (
            <Container>
                <Row>
                    <ul>
                        { this.getFruits() }
                    </ul>
                </Row>
            </Container>
        );
    }
}

export default FruitList

From this, I result in a TypeError: this.state.fruits.map is not a function. I have tried looking at other examples/errors similar, but can't seem to reason why my case is not acting properly. Any thoughts?

Thanks!

Upvotes: 0

Views: 618

Answers (3)

adrum
adrum

Reputation: 71

fruits is an object, not an array, the method map only exists natively on the array type in JavaScript.

To iterate over the key value pairs of fruits you can do either of the following:

getFruits() {
    const items = Object.keys(this.state.fruits).map(
        (key) => <li key={key}>{this.state.fruits[key]}</li>
    );
}

or

getFruits() {
    const items = Object.entries(this.state.fruits).map(
        ([key, value]) => <li key={key}>{value}</li>
    );
}

Upvotes: 1

Gustavo Kath
Gustavo Kath

Reputation: 11

You can convert it using the Object.values

const data = {
  "data": {
    "1": {
      "apple": "Delicious"
    },
    "2": {
      "orange": "It's orange."
    }
  },
  "message": "success retrieved fruits list",
  "status": 200
}

const fruits = data.data;
const list = Object.values(fruits);

console.log(list)

Upvotes: 0

Quentin Grisel
Quentin Grisel

Reputation: 4987

Try to to something like this :

Array.from(this.state.fruits).map(...)

It will change your object to an array. Take a look at Object.values that would work as well

Upvotes: 0

Related Questions