Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

On Change Search With Debounce #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect, useRef } from 'react';
import React, { useState, useEffect, useCallback , useRef } from 'react';
import axios from 'axios';
import './App.css';


const debounce = (callback, delay = 250) => {
let timeoutId
return (...args) => {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
timeoutId = null
callback(...args)
}, delay)
}
}


const API = 'http://hn.algolia.com/api/v1/search?query=';

function App() {
Expand All @@ -11,19 +24,22 @@ function App() {
const [loading, setLoading] = useState(false);
const [err, setErr] = useState('');
const searchInputRef = useRef();
const debouncecallAPI = useCallback(debounce(async (searchStr) => {
callAPI(searchStr);
}, 1000), [])

useEffect(() => {
callAPI();
}, []);
let searchStr = search;
debouncecallAPI(searchStr);
}, [search]);

const callAPI = async () => {
const callAPI = async (search) => {
if (search) {
try {
setLoading(true);
const res = await axios.get(`${API}${search}`);
setResults(res.data.hits);
setLoading(false);
setSearch('');
searchInputRef.current.focus();
} catch (err) {
setErr(err.message);
Expand All @@ -32,12 +48,12 @@ function App() {
}

const handleSearch = async (e) => {
setSearch(e.target.value);
setSearch(e.target.value)
}

const handleKeyDown = async (e) => {
if (e.keyCode === 13) {
await callAPI();
await callAPI(search);
}
}

Expand Down