So I'm trying to fetch data from my API and I'm able to log it into console, but I can't render it into my app using useState. Tried something like that and it completely ignores my h2.
var id = "61bf209bdb079818ec63d9fd";
const Main = () => {
const [name, setName] = useState("");
const [fromApi, setFromApi] = useState([]);
const getApiData = () => {
fetch('http://localhost:3000/myapi')
.then(res => {
return res.json();
})
.then(data => {
console.log(data);
setFromApi(data);
})
for (var i = 0; i < fromApi.length; i++) {
if (fromApi[i]._id === id) {
setName(fromApi[i].name);
}
}
}
useEffect(() => {
getApiData();
}, [])
return (
<div>
{name && <h2 className='urname'>Your name: {name}</h2>}
</div>
)
}
forloop should be called inside thethen()after thefetch. Currently you run thefor loopbefore the data has loaded.