In useEffect with fetch(api), I have set [search]. This shows "loading..." every time I type something in the input box and I have to click on the box to type next word/number.
I'd like to know how I can avoid it so that I can keep typing without choosing the box every single letter I typed.
I have JSON data which has "login" as the username. It would be appreciated if I could get help.
App.js file:
import React, {useState, useEffect} from "react";
import './App.css';
import UserDetails from "./UserDetails"
function App() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState('');
useEffect(() => {
if(!search) {
return;
}
setLoading(true);
fetch(`https://api.github.com/search/users?q=${search}`)
.then(res => res.json())
.then(res => {
console.log(res)
setUsers(res.items);
setLoading(false);
})
.catch(err => {
console.log(err);
});
}, [search]); // every time search changes, we call the fn
if(loading) {
return <p>Loading...</p>
}
return(
<div>
<h1>Github user searcher</h1>
<input
type="text"
placeholder="Search"
onChange={e => setSearch(e.target.value)}
value={search}
/>
{users.map((user, name) => ( // {}you have ti return inthis fn, () using this return directly
<UserDetails
key={name}
{...user}
/>
))}
</div>
)
};
export default App;
UserDetails.js file:
import React from "react"
function UserDetails(props) {
return(
<div>
{props.login}
</div>
)
}
export default UserDetails
loadingtrue. So as input changes. It settrueand thefalse. What do you want when user is typing?searchis modified, so your effect is called, and yousetLoading(true), si it destroys all your input, userDetails etc, and mounts theptag. Then aftersetLoading(false)a new input is mounted = you have lost the focus.