DEV Community

vinit kumar pandey
vinit kumar pandey

Posted on

Explain X Like I'm Five

Medium Beginners project :
Setup and working - Input’s value to search for users in GitHub using their username or email.Perform an HTTP request to a GitHub API endpoint to then fetch the users' profile which once again uses the browser fetch API. The request URL will use the input value. .
Want : I want search functionality as the user types the github email instead of having to first submit the form .Tried Debounce but didn't work .
`import { useState } from "react";
import "./styles.css";

const API_URL = "https://api.github.com";

async function fetchResults(query) {
try {
const response = await fetch(${API_URL}/search/users?q=${query});
const json = await response.json();
return json.items || [];
} catch (e) {
throw new Error(e);
}
}

export default function App() {
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);

function onSearchChange(event) {
setQuery(event.target.value);
}

async function onSearchSubmit(event) {
event.preventDefault();
const results = await fetchResults(query);
setResults(results);
}

return (



GitHub User Search


onChange={onSearchChange}
onSubmit={onSearchSubmit}
value={query}
/>

Results




{results.map((user) => (
key={user.login}
avatar={user.avatar_url}
url={user.html_url}
username={user.login}
/>
))}




);
}

function User({ avatar, url, username }) {
return (


Profile

{username}


);
}

function Form({ onSubmit, onChange, value }) {
return (


id="search"
type="text"
// onkeyup="processChange()"
placeholder="Enter username or email"
onChange={onChange}
value={value}
/>
{/* Search */}
Click me
</form>

);
}

function debounce(func, timeout = 300){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}
function saveInput(){
console.log('Saving data');
}
const processChange = debounce(() => saveInput());`

Top comments (0)