File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ import { SetStateAction } from 'react'
2+ import { UsersType } from '@/types/types'
3+ import { setItemInSessionStorage } from '@/utils/setItemInSessionStorage'
4+
5+ const fetchUsers = async (
6+ setUsers : ( value : SetStateAction < UsersType [ ] > ) => void
7+ ) => {
8+ try {
9+ const response = await fetch (
10+ 'https://jsonplaceholder.typicode.com/users' ,
11+ {
12+ method : 'GET' ,
13+ }
14+ )
15+
16+ if ( ! response . ok ) {
17+ console . error ( 'An error occurred while fetching the users.' )
18+ throw new Error ( 'Network response was not ok' )
19+ }
20+
21+ const data = await response . json ( )
22+ if ( ! data ) {
23+ console . error ( 'An error occurred while fetching the users.' )
24+ throw new Error ( 'Received data was not ok' )
25+ }
26+
27+ setUsers ( ( prev ) => {
28+ const merged = [ ...prev , ...data ]
29+ const unique = Array . from (
30+ new Map ( merged . map ( ( item ) => [ item . id , item ] ) ) . values ( )
31+ )
32+
33+ setItemInSessionStorage ( 'users' , unique )
34+
35+ return unique
36+ } )
37+ } catch ( error : unknown ) {
38+ console . error ( 'An error occurred while fetching the users.' , error )
39+ }
40+ }
41+
42+ export default fetchUsers
You can’t perform that action at this time.
0 commit comments