Reputation: 39
i'm trying to fetch a data from api and build a table for it , but nothing affiched in the page and no probleme givit from console , my code is true but something not work , the data returned is a object contain a arrays i stock the array informations what i need it into state and wante to show it
=>>>nothing in app.js
index.js
import { useState }from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';
import React from 'react';
function Generate(){
var [items,setItems]=useState([])
var url="https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita";
fetch(url)
.then((res) => res.json())
.then((data) => {
setItems(data.drinks)
},
)
return items;
}
function Work(){
let data=Generate()
return(
<table>
<tr>
<th>ID</th>
<th>LIBELLE</th>
</tr>
{
data.map(elm=>{
return(
<tr>
<td>{elm.idDrink}</td>
<td>{elm.strDrink}</td>
</tr>
)
})
}
</table>
)
}
export default function App() {
<Work />
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Upvotes: -1
Views: 840
Reputation: 41407
Move the api call inside the useEffect
function Generate(){
const [items,setItems]=useState([])
const url="https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita";
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => {
setItems(data.drinks)
},
)
}, [])
return items;
}
Upvotes: 1