|
1 | | -import React from 'react' |
| 1 | +import React from 'react'; |
| 2 | +import axios from 'axios'; |
| 3 | +import _ from 'lodash'; |
2 | 4 |
|
3 | | -import { useMyHook } from 'react-use-cancel-token' |
| 5 | +import useCancelToken from 'react-use-cancel-token'; |
4 | 6 |
|
5 | 7 | const App = () => { |
6 | | - const example = useMyHook() |
| 8 | + const [search, setSearch] = React.useState(''); |
| 9 | + const [searching, setSearching] = React.useState(false); |
| 10 | + const [result, setResult] = React.useState('No results.'); |
| 11 | + const { newCancelToken, cancelPreviousRequest, isCancel } = useCancelToken(); |
| 12 | + |
| 13 | + const performSearch = async (keywords = search) => { |
| 14 | + cancelPreviousRequest(); |
| 15 | + setSearching(true); |
| 16 | + |
| 17 | + try { |
| 18 | + const response = await axios.get( |
| 19 | + `https://api.github.com/search/repositories?q=${keywords}&sort=stars&order=desc`, |
| 20 | + { |
| 21 | + cancelToken: newCancelToken(), |
| 22 | + } |
| 23 | + ); |
| 24 | + |
| 25 | + if (response.status === 200) { |
| 26 | + setResult(response.data.items); |
| 27 | + } |
| 28 | + } catch (err) { |
| 29 | + if (isCancel(err)) return; |
| 30 | + setResult('An error occured!'); |
| 31 | + console.error(err); |
| 32 | + } |
| 33 | + |
| 34 | + setSearching(false); |
| 35 | + }; |
| 36 | + |
| 37 | + const delayedSearch = React.useCallback( |
| 38 | + _.debounce((value) => performSearch(value), 700), |
| 39 | + [performSearch] |
| 40 | + ); |
| 41 | + |
| 42 | + const handleInputChange = (event) => { |
| 43 | + const { value } = event.target; |
| 44 | + setSearch(value); |
| 45 | + delayedSearch(value); |
| 46 | + }; |
| 47 | + |
| 48 | + const handleCancel = () => { |
| 49 | + cancelPreviousRequest(); |
| 50 | + setSearching(false); |
| 51 | + }; |
| 52 | + |
7 | 53 | return ( |
8 | | - <div> |
9 | | - {example} |
10 | | - </div> |
11 | | - ) |
12 | | -} |
13 | | -export default App |
| 54 | + <> |
| 55 | + <input type="text" placeholder="Search..." value={search} onChange={handleInputChange} /> |
| 56 | + <button onClick={handleCancel} disabled={!searching}> |
| 57 | + Cancel |
| 58 | + </button> |
| 59 | + {searching && ' Searching...'} |
| 60 | + <br /> |
| 61 | + <br /> |
| 62 | + <div> |
| 63 | + {_.isArray(result) ? ( |
| 64 | + <> |
| 65 | + <h3>Github repositories:</h3> |
| 66 | + <ul> |
| 67 | + {result.map((item, index) => ( |
| 68 | + <li key={index}> |
| 69 | + <a href={item.html_url} target="_blank" rel="noopener noreferrer">{item.name}</a> |
| 70 | + </li> |
| 71 | + ))} |
| 72 | + </ul> |
| 73 | + </> |
| 74 | + ) : ( |
| 75 | + result |
| 76 | + )} |
| 77 | + </div> |
| 78 | + </> |
| 79 | + ); |
| 80 | +}; |
| 81 | +export default App; |
0 commit comments