-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathuseGiphy.js
96 lines (85 loc) · 2.14 KB
/
useGiphy.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { useState, useEffect, useReducer } from 'react'
import { getResults } from './api'
/**
* @typedef {import('./api').SearchParams} SearchParams
* @typedef {import('./api').GiphyResult} GiphyResult
* @typedef {'idle' | 'pending' | 'resolved' | 'rejected'} Status The status of the data
*
* @typedef State
* @property {Status} status
* @property {GiphyResult[]} results
* @property {Error} error
*
* @typedef Action
* @property {'started' | 'success' | 'error'} type
* @property {GiphyResult[]} [results]
* @property {Error} [error]
*/
/**
* @type {State}
*/
const INITIAL_STATE = {
status: 'idle',
results: [],
error: null,
}
/**
* Returns an updated version of `state` based on the `action`
* @param {State} state Current state
* @param {Action} action Action to update state
* @returns {State} Updated state
*/
const reducer = (state, action) => {
switch (action.type) {
case 'started': {
return {
...state,
status: 'pending',
}
}
case 'success': {
return {
...state,
status: 'resolved',
results: action.results,
}
}
case 'error': {
return {
...state,
status: 'rejected',
error: action.error,
}
}
default: {
// In case we mis-type an action!
throw new Error(`Unhandled action type: ${action.type}`)
}
}
}
/**
* @callback SetSearchParams
* @param {SearchParams} searchParams Search parameters
*/
/**
* A custom hook that returns giphy results and a function to search for updated results
* @returns {[State, SetSearchParams]}
*/
const useGiphy = () => {
const [searchParams, setSearchParams] = useState({})
const [state, dispatch] = useReducer(reducer, INITIAL_STATE)
useEffect(() => {
const fetchResults = async () => {
try {
dispatch({ type: 'started' })
const apiResponse = await getResults(searchParams)
dispatch({ type: 'success', results: apiResponse.results })
} catch (err) {
dispatch({ type: 'error', error: err })
}
}
fetchResults()
}, [searchParams])
return [state, setSearchParams]
}
export default useGiphy