Trying to figure out why the state is not being set after I fetch the data. Here is the code I am using...
const [data, setData]: any = useState({ items: [] });
useEffect(() => {
async function fetchData() {
const repsonse: any = await fetch('https://hn.algolia.com/api/v1/search?query=react');
const result: any = await repsonse.json();
//console.log(result);
setData(result.hits);
}
fetchData();
}, []);
console.log(data);
In the example above I am using hooks for useState(). Then I use a useEffect to do a fetch request. I use the setData function to set the state that I got from the request.
But when I console.log the data I get an empty array. Anyone know why this is happening? Might be something simple that I am missing.
await
fromawait repsonse.json();
- ravibagul91console.log
right aftersetData
. - Gaƫl Sresponse.json()
is indeed a promise as well. What does the result say? Any errors in your console? Add a try/catch. - Goodbye StackExchange