I'm trying to fetch data from API in react but I can't display the data on the page It appears in the console but I couldn't display it on the page
import React from 'react';
import './App.css';
function App() {
const [data, setData] = React.useState([]);
const getData = async()=>{
await fetch(`https://629e71fe3dda090f3c19d701.mockapi.io/v1/meals`,{method:"GET"})
.then((res) => res.json())
.then((response) => console.log(response));
}
React.useEffect(() => {
getData()}, []);
return (
<div className='root'>
<div className='container'>
<div className='card'>
<div className='juiceName'>{data.map((item)=>(<h1>{item.name}</h1>))}</div>
<div className='juiceImage'>{data.map((item)=>(<img >{item.image}</img>))}</div>
</div>
</div>
</div>
)
}
export default App;
CodePudding user response:
You aren't setting the data inside the component
CodePudding user response:
Instead of console.log the result of the request, try to set the state using your function setData
const getData = async()=>{
await fetch(`https://629e71fe3dda090f3c19d701.mockapi.io/v1/meals`,{method:"GET"})
.then((res) => res.json())
.then((response) => setData(response));
}
CodePudding user response:
You have to set data in fetch response, your useEffect()
hook doesn't work here.
Check it:
https://pastebin.com/btZB2fyB
CodePudding user response:
The first problem is that when you fetched the data from the API you didn't store the response inside setData();
The second problem is that you are mapping the data incorrectly, you should add the item name and item image in the same div element.
And lastly you are using the image tag incorrectly
import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
const [data, setData] = useState([]);
const getData = async () => {
await fetch(`https://629e71fe3dda090f3c19d701.mockapi.io/v1/meals`,{method:"GET"})
.then((res) => res.json())
.then((response) => setData(response));
}
useEffect(() => {
getData();
}, [])
return (
<div className='root'>
<div className='container'>
<div className='card'>
{
data.map((item, key) => {
return (
<div key={key}>
<div className='juiceName'><h1>{item.name}</h1></div>
<div className='juiceImage'><img src={item.image} alt={`Image of ${item.name}`} /></div>
</div>
)
})
}
</div>
</div>
</div>
)
}
export default App