Home > Software design >  Displaying json arrays in React
Displaying json arrays in React

Time:11-26

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//////////wEaCXVzLWVhc3QtMSJIMEYCIQDpnaXhSzGfXCmxvypbyEuHsQoaEVX9tsSxAHEAttR/uAIhAI+so6mALweGSGbfFqjijfLZYKlNjx9vofkJPPR3o4P9KtUECPr//////////wEQABoMMTg3MDE3MTUwOTg2Igw/jCzJyZGmSs+A5uQqqQT3216RtVYOtYQ68ewLqgYN3afBsemEChcI0wO9St/vk67aOwBGyJGwiaQCoLNaqIGobQXfkrtHjRPQVqNcTqtsRS4Qi+0tSSc+podO5fpBejLyaUsEtP9REXSNjWdGSS+ucN7yi5ObnF5O6DkWDxYVvA4vbisr/NkA2A7qPIyALSH7l7DQkvJDsMj+aKBxM3Ct3c019gbNplPbqL6XfG2iUPyUqGX0roUhOc2dcRLJWEh2urg6/nla97k5hCUCV437I4vlT622Zr/pDpy/vnEwUNidqbS7B3u4oGmTNbQMGSx6h5TjmHIHqDoQzPnfsWs62GxYglzS55d+JhtL2tldl3y2iR/lDMXT1ejlz5YpU2dYpJzYKiM/hzHU8h8dJcTKoqmjjKMtMsp3XEfdfC7JNN5S+KQQdgIAjL+0n4aKWkPmddsP3pHi4bHGEbDrc2GUUUjHJMUityTKPb1sEieg0//lLrhoi4Mj1+udlaT4Vmor9S4EIxnnRIDq5V0o1rUsLj784+fLBReZTCPa+OxT0ZpF/Jyl9dZfakqCEXSdjWjzX07b08uTzYJIfyfwKHWrzW32wJ4aRUR7WdCcJ3n0rmjgpqKX6ozOeS8R5TP7HFeyVQcWcCyzmKDCSV40y761TasY+V5sqlURzjBL8/2iyztTydDhjopyQ1PBiewJeA06oRY4Ql3WiEySmRI4GwHOzyJOy7GY/r27ZuVRolbX+P+workCZpLrMMLAhZwGOqgBSIfkg1IG0s7EX17nVG89NMfvCCN4WXfempWOHkP2qAZtXrZOHyumjT4DUY2rDbbcqmVYBKAysjFa9NE+ceP7+BNXLBBh4/MmaqvjZP1DYaRAj1ldEZr7E+NuLrADKB0Vb2pWv7mLYMcTzXzcOOLeabpSMPMsPyLNqkOr+peryDw6pSGebOajGpQA0QTV1m4z3HijmRicL2LLW4q5RooyF2oR5QKBu8/k&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20221126T013542Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Credential=ASIASXCYXIIFP4CCVRCC/20221126/us-east-1/s3/aws4_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,egg,spinach",
"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 ?

CodePudding user response:

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.

  • Related