i’m trying to implement search functionality but i don’t want to call the api every time i type something . here is the code:
JavaScript
x
24
24
1
const [term, setTerm] = useState("");
2
const [result, setResult] = useState([]);
3
4
useEffect(() => {
5
const search = async () => {
6
const respond = await axios.get("https://en.wikipedia.org/w/api.php", {
7
params: {
8
action: "query",
9
list: "search",
10
origin: "*",
11
format: "json",
12
srsearch: term,
13
},
14
});
15
setResult(respond.data.query.search);
16
};
17
18
if (!result.length) {
19
if (term) {
20
search();
21
}
22
}
23
}, [term, result.length]);
24
Advertisement
Answer
you can use the setTimeout() function and clearTimeout in the cleanup function and the useRef hook to get the previous state to call the API only once :
JavaScript
1
43
43
1
const [result, setResult] = useState([]);
2
const termUseRef = useRef();
3
4
useEffect(() => {
5
termUseRef.current = term
6
7
})
8
9
const prevTerm = termUseRef.current;
10
11
12
useEffect(() => {
13
const search = async () => {
14
const respond = await axios.get('https://en.wikipedia.org/w/api.php', {
15
params: {
16
action: 'query',
17
list: 'search',
18
origin: '*',
19
format: 'json',
20
srsearch: term,
21
},
22
});
23
setResult(respond.data.query.search);
24
};
25
26
if (!result.length) {
27
if (term) {
28
search();
29
}
30
31
} else if(term !== prevTerm) {
32
const debounceSearch = setTimeout(() => {
33
if (term) {
34
search();
35
}
36
}, 1200);
37
38
return () => {
39
clearTimeout(debounceSearch);
40
};
41
}
42
}, [term, result.length, prevTerm]);
43