-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
48 lines (41 loc) · 1.21 KB
/
App.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
import React, { useState, useRef, useCallback } from 'react'
import useBookSearch from './useBookSearch'
export default function App() {
const [query, setQuery] = useState('')
const [pageNumber, setPageNumber] = useState(1)
const {
books,
hasMore,
loading,
error
} = useBookSearch(query, pageNumber)
const observer = useRef()
const lastBookElementRef = useCallback(node => {
if (loading) return
if (observer.current) observer.current.disconnect()
observer.current = new IntersectionObserver(entries => {
if (entries[0].isIntersecting && hasMore) {
setPageNumber(prevPageNumber => prevPageNumber + 1)
}
})
if (node) observer.current.observe(node)
}, [loading, hasMore])
function handleSearch(e) {
setQuery(e.target.value)
setPageNumber(1)
}
return (
<>
<input type="text" value={query} onChange={handleSearch}></input>
{books.map((book, index) => {
if (books.length === index + 1) {
return <div ref={lastBookElementRef} key={book}>{book}</div>
} else {
return <div key={book}>{book}</div>
}
})}
<div>{loading && 'Loading...'}</div>
<div>{error && 'Error'}</div>
</>
)
}