I am trying to fetch data but its always undefined once it gets to my return.. which makes sense because I am no longer using .then at that point. React doesnt seem to let me make the function Async so I cant really use await either? I tried setting it with useState but its still undefined where I need to use the data.
const [myData,setData] = useState('')
useEffect(() => {
fetch('https://recipesapi2.p.rapidapi.com/recipes/tomato%20soup', options)
.then((data) => data.json())
.then((data) => {
setData(data.data); console.log('this is my data', data.data)
})
.then(()=>console.log(myData))
},[])
return(
<div>{myData[0].name}</div>
) }
I would also like to note that if I remove the return, and then wait for the page to respond with the data in the log, then add the return info back, it displays the div info properly. However, if i hard refresh the browser it runs nothing, not even my console logs. So that tells me I am inputting the proper code to populate the div but its not awaiting the fetch and just throwing errors.
setData(data.data), make itsetData(data.data); console.log('this is my data', data.data);so you can debug it. And let us know what it prints.then(console.log(myData))doesn't make sense. It should probably be.then(() => { console.log(myData); })and while we're at it, it's better to make it a.then(() => { console.log(myData); }).catch((e) => { console.log('error!', e); })0and addition of the arrow function (and else)? This should make it easier for us to talk under a common ground