Reputation: 489
Hellooo,
This is my first time using React. I want to fetch some data in json format and list it out in my page. The code below is not working.
import React, { useState, useEffect } from "react";
import axios from "axios";
function DataFetching() {
const [users, setUsers] = useState({ hits: [] });
//const [query, setQuery] = useState("redux");
useEffect(async () => {
const fetchData = async () => {
const result = await axios("url");
setUsers(result.data);
};
}, []);
return (
<div>
<p>Hellooooo</p>
<ul>
{users.hits.map((user) => (
<li key={user.id}>{user.title}</li>
))}
</ul>
</div>
);
}
export default DataFetching;
Upvotes: 0
Views: 948
Reputation: 202741
useEffect
hook callbacks are 100% synchronous, they can't be asynchronous (i.e. declared async
) at all. This also implicitly returns a Promise and messes with the effect cleanup functionality.fetchData
function, so nothing is really updated.hits
key.async
keyword from the effect callback.fetchData
in the effect callback body.Code:
useEffect(() => {
const fetchData = async () => {
try {
const result = await axios("url");
setUsers({ hits: result.data });
} catch(error) {
// handle any GET request or response handling errors
}
};
fetchData();
}, []);
Upvotes: 6