xif
xif

Reputation: 343

How to use map function with JSON object fetch though an API

I fetch data from my api, JSON is :

{
    "food": [
        {
            "food": "Not Handle",
            "nb": 49
        },
        {
            "food": "Cooked",
            "nb": 1
        },
        {
            "food": "Raw",
            "nb": 1
        },
    ]
}

My data are stored in my state when the component didMount so this.state.food contain my JSON data

I tried to to render it like this:

render() {
    return (
        <Row>
            {this.state.food &&
                this.state.food.map((food) => {
                    return (
                        <div >
                            <Col sm={12} md className="mb-sm-2 mb-0">
                                <div className="text-muted">{food.food} :</div>
                                <strong> {food.nb}</strong>
                            </Col>
                        </div>)
                })}
        </Row>
    )
}

CompenentDidMount : (getCall is a custom function to fetch)

async componentDidMount () {
const food = await getCall(
    `stats/event/count/food?eventRef=${this.props.eventRef}`,
    this.props.authToken,
    false
  );
  console.log('DATA', food); //  printed my data perfectly
  this.setState({ food: food});
}

I think I miss something, because I can't map on this object I get map is not a function, I saw it's only an array ?

expected result is really simple i want to display :

Not handle: 49
Cooked: 1
Raw: 1

Upvotes: 2

Views: 1303

Answers (2)

Anitta Paul
Anitta Paul

Reputation: 465

After your api call change the setState statement to this.setState({ food: food.food});

What you are getting as response from your api is json. so you are trying to use map function on a json. map function could only be used with array.

Upvotes: 1

Arpit Agrawal
Arpit Agrawal

Reputation: 1180

Try this :

async componentDidMount () {
const data = await getCall(
    `stats/event/count/food?eventRef=${this.props.eventRef}`,
    this.props.authToken,
    false
  );
  console.log('DATA', data); //  printed my data perfectly
  this.setState({ food: data.food});
}

Assumption : await getCall() return this exact data :

{
    "food": [
        {
            "food": "Not Handle",
            "nb": 49
        },
        {
            "food": "Cooked",
            "nb": 1
        },
        {
            "food": "Raw",
            "nb": 1
        },
    ]
}

if this is exactly what is returned from getCall(), then you are getting confused due to wrong variable name. Data is actually a map with one key as food which is the array. So in state you have to actually get the value of food key from data which has map function.

Upvotes: 2

Related Questions