Best Practices for Fetching Data in React Call API on Page Load
https://www.dhiwise.com/post/best-practices-for-fetching-data-in-react-call-api-on-page-load
function Posts() {
2  const [posts, setPosts] = useState([]);
3  const [loading, setLoading] = useState(true);
4  const [error, setError] = useState(null);
5
6  useEffect(() => {
7    fetch('https://jsonplaceholder.typicode.com/posts')
8      .then(response => response.json())
9      .then(data => {
10        setPosts(data);
11        setLoading(false);
12      })
13      .catch(err => {
14        setError(err);
15        setLoading(false);
16      });
17  }, []);
18
19  if (loading) return <div>Loading...</div>;
20  if (error) return <div>Error: {error.message}</div>;
21
22  return (
23    <ul>
24      {posts.map(post => (
25        <li key={post.id}>{post.title}</li>
26      ))}
27    </ul>
28  );
29}
 
Không có nhận xét nào:
Đăng nhận xét