Created
April 14, 2020 08:45
-
-
Save kylemocode/3f3b20c0112c1d80c1878c1007342df6 to your computer and use it in GitHub Desktop.
This file contains 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
import { useEffect, useState } from 'react'; | |
import axios from 'axios'; | |
import { DCARD_POPULAR_POSTS_BASE_URL, API_POST_LIMIT } from '../constant/api'; | |
export interface FetchPostHook { | |
loading: boolean; | |
error: boolean; | |
posts: any[]; | |
hasMore: boolean; | |
} | |
export default function useFetchPost(lastId?: number | null) { | |
const [loading, setLoading] = useState(true); | |
const [error, setError] = useState(false); | |
const [posts, setPosts] = useState([]); | |
const [hasMore, setHasMore] = useState(true); | |
useEffect(() => { | |
setLoading(true); | |
setError(false); | |
if (lastId) { | |
setTimeout(() => { | |
axios.get(DCARD_POPULAR_POSTS_BASE_URL + '&limit=' + API_POST_LIMIT + '&before=' + lastId) | |
.then((result) => { | |
// @ts-ignore | |
setPosts(prevPosts => { | |
return [...prevPosts, ...result.data] | |
}); | |
setHasMore(result.data.length > 0) | |
setLoading(false); | |
}) | |
.catch(() => { | |
setError(true); | |
}) | |
}, 700) | |
} else { | |
// 第一次進入頁面 | |
axios.get(DCARD_POPULAR_POSTS_BASE_URL + '&limit=' + API_POST_LIMIT) | |
.then((result) => { | |
setPosts(result.data); | |
setLoading(false); | |
}) | |
.catch(() => { | |
setError(true); | |
}) | |
} | |
}, [lastId]) | |
return { loading, error, posts, hasMore }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment