-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathuseGifs.js
More file actions
42 lines (32 loc) · 1.26 KB
/
useGifs.js
File metadata and controls
42 lines (32 loc) · 1.26 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
import {useContext, useEffect, useState} from 'react'
import getGifs from '../services/getGifs'
import GifsContext from '../context/GifsContext'
const INITIAL_PAGE = 0
export function useGifs ({ keyword, rating } = { keyword: null }) {
const [loading, setLoading] = useState(false)
const [loadingNextPage, setLoadingNextPage] = useState(false)
const [page, setPage] = useState(INITIAL_PAGE)
const {gifs, setGifs} = useContext(GifsContext)
// recuperamos la keyword del localStorage
const keywordToUse = keyword || localStorage.getItem('lastKeyword') || 'random'
useEffect(function () {
setLoading(true)
getGifs({ keyword: keywordToUse, rating })
.then(gifs => {
setGifs(gifs)
setLoading(false)
// guardamos la keyword en el localStorage
gifs.length && localStorage.setItem('lastKeyword', keywordToUse)
})
}, [keyword, keywordToUse, rating, setGifs])
useEffect(function () {
if (page === INITIAL_PAGE) return
setLoadingNextPage(true)
getGifs({ keyword: keywordToUse, page, rating })
.then(nextGifs => {
setGifs(prevGifs => prevGifs.concat(nextGifs))
setLoadingNextPage(false)
})
}, [keywordToUse, page, rating, setGifs])
return {loading, loadingNextPage, gifs, setPage}
}