'set and remove attribute only works in one of two cases
On every letter user types, github profiles are fetched and for that I'm using set attribute to hide or show loading(spinning) sign, when user types something in search bar it unhides loading sign and shows until data is fetched, but problem is that when user Types only 1 letter it doesn't work, and doesn't unhide sign but after data fetching works fine, when user types two letter at time, remove attribute works and shows loading sign and after data is fetched it hides loading sign, so the problem is that remove attribute only works when use types 2 or more letter at time and doesn't work when user types only 1 letter at time.
function SearchBox() {
const [searchValue, setSearchValue] = useState('');
const [profiles, setProfiles] = useState([]);
const [show, setShow] = useState(false);
const [hoverValue, setHoverValue] = useState('');
const [spinner1, setSpinner] = useState(false);
const finalSearchValue = searchValue + hoverValue;
useEffect(() => {
const spinner = document.getElementById("spinner");
const getSearchedProfile = async (searchValue) => {
const api_url = 'https://api.github.com/search/users?q='+searchValue+'+in:login&per_page=10';
const fetchProfile = await fetch(api_url);
const profile = await fetchProfile.json();
if(spinner){
spinner.setAttribute('hidden', '');
}
setSpinner(false);
setProfiles(profile.items);
}
const getPoPularProfile = async () => {
const api_url = 'https://api.github.com/search/users?q=repos:%3E800+followers:%3E1000&page=1&per_page=10';
const fetchProfile = await fetch(api_url);
const profile = await fetchProfile.json();
setProfiles(profile.items);
}
if(searchValue !== ''){
setSpinner(true);
if(spinner){
spinner.removeAttribute('hidden');
}
const timer = setTimeout(() => {
getSearchedProfile(searchValue);
setShow(true);
}, 2200);
return () => clearTimeout(timer);
}
if(searchValue === ''){
getPoPularProfile();
setShow(false);
setSpinner(false);
}
}, [searchValue])
return (
<div className='fullPage'>
<div className='searchBar'>
<h1 className='header-text'>Github Profile Finder</h1>
<div className='input-wrapper'>
<input onChange={(event) => setSearchValue(event.target.value)}
placeholder='Enter name'
value={finalSearchValue}
className='inputBar'
spellCheck="false" />
<span className='input-highlight'>
{ finalSearchValue.replace(/ /g, "\u00a0") }
</span>
</div>
{show ? '' : <h2 className='popular-text'>Popular github users</h2>}
</div>
<div className='profilesList'>
{spinner1 ? <div hidden id="spinner"></div> : <Profiles showProfiles={profiles}
setHoverValue={setHoverValue}
searchValue={searchValue}
setSearchValue={setSearchValue}/>}
</div>
</div>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
