how to access and display rates object fetched from api?

Viewed 20

I fetch data from api .it shows ALL results on console .also on screen all values are displaying but rates object gives error. this is my API structure. {"success":true,"timestamp":1615562100,"date":"2021-03-12","base":"USD","rates":{"USD":1,"XAG":0.03901943185,"XAU":0.00058730524,"XPD":0.00042789653698162,"XPT":0.00083160432252702,"XRH":3.8192366412214e-5},"unit":"per ounce"}

so can anybody help how rates object be displayed on screen.?

1 Answers

Use Object.prototype.values or Object.prototype.entries because React not render object in normal way.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin ></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin ></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> 
    <script type="text/babel">
      const {useEffect, Fragment} = React;  

      const data = {"success":true,"timestamp":1615562100,"date":"2021-03-12","base":"USD","rates":{"USD":1,"XAG":0.03901943185,"XAU":0.00058730524,"XPD":0.00042789653698162,"XPT":0.00083160432252702,"XRH":3.8192366412214e-5},"unit":"per ounce"}

      const App = (props) => {
        return (
          <ul>
            {
              data && data.rates && Object.entries(data.rates).map(([key, value]) => 
                <li key={key}>
                   {`${key}: ${value}`} 
                </li>  
              )
            }
          </ul>
        );
      };

      ReactDOM.render(<App name="123" onKeyDown={()=>console.log('keydown')} />, document.getElementById("root"));
    </script>
  </body>
</html>

Related