0

I'm using React to display data,and I want to display data inside hits, which is array of recipes.Below is the structure. I want to list the properties inside each recipe. enter image description here

recipe": {
"uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_d090689494d5bc05e53e4a808bf6db1c",
"label": "Recipe For (A Kind Of) Pisto, With Rice And Eggs",
"image": "https://edamam-product-images.s3.amazonaws.com/web-img/b7c/b7c8284b065e055f74c59f3f88718b84.jpg?X-Amz-Security-Token=IQoJb3JpZ2luX2VjEPH%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJIMEYCIQDpnaXhSzGfXCmxvypbyEuHsQoaEVX9tsSxAHEAttR%2FuAIhAI%2Bso6mALweGSGbfFqjijfLZYKlNjx9vofkJPPR3o4P9KtUECPr%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEQABoMMTg3MDE3MTUwOTg2Igw%2FjCzJyZGmSs%2BA5uQqqQT3216RtVYOtYQ68ewLqgYN3afBsemEChcI0wO9St%2Fvk67aOwBGyJGwiaQCoLNaqIGobQXfkrtHjRPQVqNcTqtsRS4Qi%2B0tSSc%2BpodO5fpBejLyaUsEtP9REXSNjWdGSS%2BucN7yi5ObnF5O6DkWDxYVvA4vbisr%2FNkA2A7qPIyALSH7l7DQkvJDsMj%2BaKBxM3Ct3c019gbNplPbqL6XfG2iUPyUqGX0roUhOc2dcRLJWEh2urg6%2Fnla97k5hCUCV437I4vlT622Zr%2FpDpy%2FvnEwUNidqbS7B3u4oGmTNbQMGSx6h5TjmHIHqDoQzPnfsWs62GxYglzS55d%2BJhtL2tldl3y2iR%2FlDMXT1ejlz5YpU2dYpJzYKiM%2FhzHU8h8dJcTKoqmjjKMtMsp3XEfdfC7JNN5S%2BKQQdgIAjL%2B0n4aKWkPmddsP3pHi4bHGEbDrc2GUUUjHJMUityTKPb1sEieg0%2F%2FlLrhoi4Mj1%2BudlaT4Vmor9S4EIxnnRIDq5V0o1rUsLj784%2BfLBReZTCPa%2BOxT0ZpF%2FJyl9dZfakqCEXSdjWjzX07b08uTzYJIfyfwKHWrzW32wJ4aRUR7WdCcJ3n0rmjgpqKX6ozOeS8R5TP7HFeyVQcWcCyzmKDCSV40y761TasY%2BV5sqlURzjBL8%2F2iyztTydDhjopyQ1PBiewJeA06oRY4Ql3WiEySmRI4GwHOzyJOy7GY%2Fr27ZuVRolbX%2BP%2BworkCZpLrMMLAhZwGOqgBSIfkg1IG0s7EX17nVG89NMfvCCN4WXfempWOHkP2qAZtXrZOHyumjT4DUY2rDbbcqmVYBKAysjFa9NE%2BceP7%2BBNXLBBh4%2FMmaqvjZP1DYaRAj1ldEZr7E%2BNuLrADKB0Vb2pWv7mLYMcTzXzcOOLeabpSMPMsPyLNqkOr%2BperyDw6pSGebOajGpQA0QTV1m4z3HijmRicL2LLW4q5RooyF2oR5QKBu8%2Fk&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20221126T013542Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Credential=ASIASXCYXIIFP4CCVRCC%2F20221126%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=68656c34e850742a7b45117e905bbb71babec459015201e4246e65a5d6946d3b",
"source": "Mostly Eating",
"url": "http://www.mostlyeating.com/in-praise-of-pisto-and-a-perfectly-balanced-meal",
"shareAs": "http://www.edamam.com/recipe/recipe-for-a-kind-of-pisto-with-rice-and-eggs-d090689494d5bc05e53e4a808bf6db1c/tomato%2Cegg%2Cspinach",
"yield": 2.0,
"dietLabels": [
"Balanced",
"High-Fiber"
],
"healthLabels": [
"Vegetarian",
"Pescatarian",
"Dairy-Free",
"Gluten-Free",
"Wheat-Free",
"Peanut-Free",
"Tree-Nut-Free",
"Soy-Free",
"Fish-Free",
"Shellfish-Free",
"Pork-Free",
"Red-Meat-Free",
"Crustacean-Free",
"Celery-Free",
"Mustard-Free",
"Sesame-Free",
"Lupine-Free",
"Mollusk-Free",
"Alcohol-Free",
"Kosher"
],
"cautions": [ ]
}

Here is my code.

import React, { Component } from 'react';
import axios from 'axios'
import CallAPI from './CallAPI';

const api = 'http://localhost:5000' // backend address

class GetRecipe extends Component{
    constructor(props){
        super(props)
        this.state={
            list:[]
        }
        this.setState=this.setState.bind(this)
    }
    
    getData=()=>{
        var url = `${api}/getRecipe`;
        axios.get(url)
        .then(response=>{
            console.log(response.data)
            this.setState({list:response.hits})
        }).catch(err=>console.log(err))
    }
    render(){
        return(
            <div>         
                <h2>Get Recipe</h2>  
                <button onClick={this.getData}>Get</button>
               <p>{this.state.list}</p>
            </div>

        )
    }
}

export default GetRecipe;

Using the above code, there is no error, but nothing display in the page. So I tried another way:

<ul>
                    {this.state.list.map((value, key)=>{
                        return<li key={key}>{value}</li>
                    })}
                </ul>

However, in this way I got error

getRecipe.js:37 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
    at GetRecipe.render (getRecipe.js:37:1)

I also try to change the getData function, then I got TypeError: Cannot read properties of undefined (reading 'setState').

getData(){
        axios.get(`${api}/getRecipe`)
        .then((response)=>{
            this.setState({list:response.data})
        })
        .catch(function (error){
            console.log(error)
        })
    }

I try this way of displaying dat before, but I don't know why it doesn't work this time. How can i make it work ?

1 Answer 1

1

In your first try, you have this line:

this.setState({list:response.hits})

This should (probably) be:

this.setState({list:response.data.hits})

This resolves your (first) TypeError.

Then you try to render it like this:

<p>{this.state.list}</p>

What is React supposed to do with this? It won't magically create HTML elements for your array.

Mapping over the array is the correct way to render an element per item in the array. But:

return<li key={key}>{value}</li>

value is a plain object. How is React supposed to render it? And consider using a real key, not just the array index.

Your change of getData() makes it forget this. You probably meant to bind it in the constructor instead of setState(). This resolves your second TypeError. Or change it back to an arrow function.

Sign up to request clarification or add additional context in comments.

4 Comments

Though these error disapper after I fix them, other errors come out...Still very helpful. And a follow-up question: if I want to use ''return<li key={key}>{value}</li>'', that means my array should be something like [1, 2, 3], and each object inside the array has no internal feature?
I'm not sure I understand your question. You have an array of recipes there (which are objects), not just numbers.
I mean in this condition I have objects, so I should find other way of dislaying, instead of using just arrays.map.
Just like you wouldn't write a JS object into your HTML. Using {value.label} would be a start.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.