Home > Mobile >  Print json from api in React
Print json from api in React

Time:08-04

I have a php api that selects the database and returns this data in json, I would like to show them in a table in React App. I tried this way but got no result:

import React from 'react'
import JsonData from 'http://localhost/index.php' //My test api is index.php
 function Body(){
    const DisplayData=JsonData.map(
        (info)=>{
            return(
                <tr>
                    <td>{info.id}</td>
                    <td>{info.name}</td>
                </tr>
            )
        }
    )
 
    return(
        <div>
            <table >
                <thead>
                    <tr>
                    <th>ID</th>
                    <th>Nome</th>
                    </tr>
                </thead>
                <tbody>
                 
                    
                    {DisplayData}
                    
                </tbody>
            </table>
             
        </div>
    )
 }
 
 export default Body;

CodePudding user response:

You can't make an API call that way in react.

To make the API call you can use the fetch function, or rely on external libraries such as axios.

example with fetch:

componentDidMount() {
    // Simple GET request using fetch
    fetch('http://localhost/index.php')
        .then(response => response.json())
        .then(data => this.setState({ myCoolJSON: data}));
}

Remember that the call is made asynchronously.

CodePudding user response:

You have a few problems in your code,

first you should use an http client to fetch your data e.g. fetch, axios, etc

second you should use a state to manage your data because you should re-render your component after your data is fetched, or you may reconsider your components composition in a way that your component get mounted in the page only after your data is ready (and the pass the ready data as prop).

this is a working example using your code:

https://codesandbox.io/s/fervent-chaum-uxwexq?file=/src/App.js

Here is the request function

async function fetchData() {
  const url = "https://dummyjson.com/carts";
  const r = await (await fetch(url)).json();
  return r.carts[0].products;
}

This defined the state and makes a call after the component is mounted:

  const [rows, setRows] = React.useState([]);
  async function fetchRows() {
    setRows(await fetchData());
  }
  React.useEffect(() => fetchRows, []);

also consider using a key attribute when you're rendering a list using .map()

  • Related