I’m trying fetch data every time user types something(using useEffect for that), also I want to delay fetch function using setTimeout, so when user stops typing, it should wait 3 second and then fetch github profiles, but when i type let’s say “giorgi”, after 3 seconds instead of getting only “giorgi” profiles, it waits 3 seconds goes through all of the past fetches, first rapidly renders profiles containing gi, after that gio, then gior and etc and finally only giorgi profiles. I think I’m doing something wrong in settimeout function or I’m not using it right.
useEffect(() => {
const getSearchedProfile = async (searchValue) => {
const api_url = 'https://api.github.com/search/users?q='+searchValue+'+in:login&per_page=20';
const fetchProfile = await fetch(api_url);
const profile = await fetchProfile.json();
setProfiles(profile.items);
}
const getPoPularProfile = async () => {
const api_url = 'https://api.github.com/search/users?q=repos:followers:%3E35000&language:javascript&page=1&per_page=10';
const fetchProfile = await fetch(api_url);
const profile = await fetchProfile.json();
setProfiles(profile.items);
}
if(searchValue !== ''){
setTimeout(() => {
getSearchedProfile(searchValue);
setShow(true);
}, 3000);
}
if(searchValue === ''){
setTimeout(() => {
getPoPularProfile();
setShow(false);
}, 3000);
}
}, [searchValue])