I want to display the response from my fetch request in react. So far, I built the fetch request and set up the useEffect and useState hooks. The response is an object. What am I doing wrong?
function App() {
const url = 'https://api.gemini.com/v1/book/btcusd'
const [orders, setOrders] = useState([])
const fetchData = () => {
fetch(url).then(response => {
return response.json();
}).then(data => {
console.log(data)
setOrders(data)
}).catch(error => {
console.log(error)
})
}
useEffect(() => {
fetchData()
}, [])
return (
<div className="App">
<h1>{orders.asks}</h1>
</div>
);
}
export default App;
CodePudding user response:
Your data is an object. You should use map
to loop.
const url = "https://api.gemini.com/v1/book/btcusd";
const [orders, setOrders] = useState([]);
const fetchData = () => {
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data); //Data: {bids: Array(50), asks: Array(50)}
setOrders(data);
})
.catch((error) => {
console.log(error);
});
};
useEffect(() => {
fetchData();
}, []);
return (
<div className="App">
{orders.asks?.map((e) => {
return (
<>
<h1>{e.price}</h1>
<h1>{e.amount}</h1>
</>
)
})}
</div>
);
CodePudding user response:
Taking a quick look at that API, the asks
property holds an array of objects. You would need to map those to JSX elements in order to display them.
Also, if orders
is meant to be an object, you should not initialise it as an array.
Finally, you should always check the Response.ok property to see if the request resolved successfully.
// fetch-data.js
const url = "https://api.gemini.com/v1/book/btcusd";
export const fetchData = async () => {
const res = await fetch(url);
if (!res.ok) {
throw Object.assign(new Error(`${res.status}: ${res.statusText}`), {
url,
text: await res.text(),
});
}
return res.json();
};
// App.jsx
import { useEffect, useState } from "react";
import { fetchData } from "./fetch-data";
function App() {
// init with an object with empty `asks` array
const [orders, setOrders] = useState({ asks: [] });
useEffect(() => {
fetchData().then(setOrders).catch(console.error);
}, []);
return (
<div className="App">
{/* Map over the data */}
{orders.asks.map(({ price, amount }, i) => (
<dl key={i}>
<dt>Price</dt>
<dd>{price}</dd>
<dt>Amount</dt>
<dd>{amount}</dd>
</dl>
))}
</div>
);
}
export default App;
CodePudding user response:
You Can use map function to display each item
eg:
orders.asks.map(item=>
<div>
<h1>{item.price}</h1>
<h1>{item.amount}</h1>
</div>
)