-
-
Save rezwan-hossain/ad70a524b259a243b277183f6c061267 to your computer and use it in GitHub Desktop.
basic data fetching in react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| "use client"; | |
| import { useEffect, useRef, useState } from "react"; | |
| const BASE_URL = "https://jsonplaceholder.typicode.com"; | |
| interface Post { | |
| id: number; | |
| title: string; | |
| } | |
| export default function FetchExample1() { | |
| const [error, setError] = useState(); | |
| const [isLoading, setIsLoading] = useState(false); | |
| const [posts, setPosts] = useState<Post[]>([]); | |
| const [page, setPage] = useState(0); | |
| const abortControllerRef = useRef<AbortController | null>(null); | |
| useEffect(() => { | |
| const fetchPosts = async () => { | |
| abortControllerRef.current?.abort(); | |
| abortControllerRef.current = new AbortController(); | |
| setIsLoading(true); | |
| try { | |
| const response = await fetch(`${BASE_URL}/posts?page=${page}`, { | |
| signal: abortControllerRef.current?.signal, | |
| }); | |
| const posts = (await response.json()) as Post[]; | |
| setPosts(posts); | |
| } catch (e: any) { | |
| if (e.name === "AbortError") { | |
| console.log("Aborted"); | |
| return; | |
| } | |
| setError(e); | |
| } finally { | |
| setIsLoading(false); | |
| } | |
| }; | |
| fetchPosts(); | |
| }, [page]); | |
| if (error) { | |
| return <div>Something went wrong! Please try again.</div>; | |
| } | |
| return ( | |
| <div className="tutorial"> | |
| <h1 className="mb-4 text-2xl">Data Fething in React</h1> | |
| <button onClick={() => setPage(page - 1)}>Decrease Page ({page})</button> | |
| <button onClick={() => setPage(page + 1)}>Increase Page ({page})</button> | |
| {isLoading && <div>Loading...</div>} | |
| {!isLoading && ( | |
| <ul> | |
| {posts.map((post) => { | |
| return <li key={post.id}>{post.title}</li>; | |
| })} | |
| </ul> | |
| )} | |
| </div> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment