Skip to content

Commit 9abea41

Browse files
fetch api data
1 parent 2422afb commit 9abea41

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/api/fetchFeedItems.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { RefObject, SetStateAction } from 'react'
2+
3+
const fetchFeedItems = async (
4+
nextPage: RefObject<number>,
5+
PAGE_SIZE: number,
6+
setFeedItems: (
7+
value: SetStateAction<
8+
{
9+
postId: number
10+
id: number
11+
name: string
12+
email: string
13+
body: string
14+
}[]
15+
>
16+
) => void
17+
) => {
18+
try {
19+
const response = await fetch(
20+
`https://jsonplaceholder.typicode.com/comments?_page=${nextPage.current}&_limit=${PAGE_SIZE}`,
21+
{
22+
method: 'GET',
23+
}
24+
)
25+
26+
if (!response.ok) {
27+
console.error('An error occurred while fetching the photos.')
28+
throw new Error('Network response was not ok')
29+
}
30+
31+
const data = await response.json()
32+
if (!data) {
33+
console.error('An error occurred while fetching the photos.')
34+
throw new Error('Received data was not ok')
35+
}
36+
setFeedItems((prev) => [...prev, ...data])
37+
nextPage.current++
38+
} catch (error: unknown) {
39+
console.error('An error occurred while fetching the photos.', error)
40+
}
41+
}
42+
43+
export default fetchFeedItems

0 commit comments

Comments
 (0)