-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseEvent.ts
More file actions
54 lines (46 loc) · 1.62 KB
/
useEvent.ts
File metadata and controls
54 lines (46 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { useCallback, useEffect, useState } from 'react'
import { ROUTES } from '@/config'
import api from '@/services/api'
import { type EventProps, FakeEvent } from '@/types/event'
export function useEvent() {
const [data, setData] = useState<EventProps[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const generateMockEvents = useCallback((): EventProps[] => {
return Array.from({ length: 10 }, (_, i) => ({
...FakeEvent,
id: i + 1,
title: `Evento mock #${i + 1}`,
description: `Descrição do evento mock #${i + 1}`,
}))
}, [])
const fetchData = useCallback(async () => {
setLoading(true)
setError(null)
try {
const response = await api.get<EventProps[]>(`${ROUTES.EVENTS}`)
let payload = Array.isArray(response.data) ? response.data : []
if (
process.env.NODE_ENV === 'development' &&
payload.length === 0
) {
payload = generateMockEvents()
}
setData(payload)
} catch {
if (process.env.NODE_ENV === 'development') {
setData(generateMockEvents())
setError(null)
} else {
setData([])
setError('Não foi possível carregar os eventos.')
}
} finally {
setLoading(false)
}
}, [generateMockEvents])
useEffect(() => {
fetchData()
}, [fetchData])
return { data, loading, error, refetch: fetchData }
}