Search code examples
javascripthtmlreactjsdjangoweb

Json displaying blank


I'm making a request from a json file in a webpage, but is returning a blank screen.

import { useEffect, useState } from 'react';
import axios from 'axios'
import './App.css';
import React from 'react';


function App() {

    const [posts, setPosts] = useState([])

    useEffect(() => {
      axios.get("https://economia.awesomeapi.com.br/json/last/USD-BRL")
      .then((response) => {
        console.log("ok")
        console.log(response.data)
        setPosts(response.data)
      }).catch(() => {
        console.log("erro")
      })
    
  }, [])

  return (
    <div>
      {posts?.map((post, key) =>{
      return(  
      <div key={key}>
        <td></td>
        <td>Dolar</td>
        <td>{post.bid}</td>
        <td>{post.create_date}</td>
      </div>)
    })}

  );
}

export default App;

The console is able to see the json file, but the page on the browser is completely blank:

I tried many json files, and only one worked out, was this one: https://api.covid19api.com/countries

I had this same problem using React and Django.


Solution

  • I think you need to map like below for the keys of an object

    import { useEffect, useState } from "react";
    import axios from "axios";
    
    function App() {
      const [posts, setPosts] = useState([]);
    
      useEffect(() => {
        axios
          .get("https://economia.awesomeapi.com.br/json/last/USD-BRL")
          .then((response) => {
            console.log("ok");
            console.log(response.data);
            console.log(response.data.USDBRL);
            console.log(response.data.USDBRL.bid);
            console.log(response.data.USDBRL.create_date);
            setPosts(response.data.USDBRL);
          })
          .catch(() => {
            console.log("erro");
          });
      }, []);
    
      return (
        <>
          {Object.keys(posts).map((keyName, i) => {
        if (keyName === "bid") {
          return (
            <li className="travelcompany-input" key={i}>
              <span className="input-label">
                Bid: {posts["bid"]}
                Create Date: {posts["create_date"]}
              </span>
            </li>
          );
        }
      })}
        </>
      );
    }
    
    export default App;
    

    and the result is like below

    enter image description here