Essentially, when I run tests on my App.tsx, the function passed into setTimeout is not being executed.
I used the debugger to see the call stack and how the code executes and everything was fine until it reached the setTimout function and the function I passed into setTimeout was not executed. When I put the if statement outside the setTimout, that code gets executed, but when I put it back into setTimeout, it does not execute. I also tried to play around with the time that i pass into the setTimeout function, but that still doesn’t work.
I have also checked that in my tests I am indeed pressing the button in order to trigger the OnSearch function, which does indeed get triggered, but once it reaches the setTimout function line, it stops.
Can anyone give me advice on how to fix this issue and have the code inside setTimeout function execute?
Code:
import React, { useEffect, useState } from "react";
import "./App.css";
import { DisplayUser } from "./components/user";
import { GithubUsersProvider } from "./providers/github-users-provider";
import { User } from "./providers/users-provider";
function App() {
const githubUsersProvider = new GithubUsersProvider();
const [queryUser, setQueryUser] = useState("");
const [users, setUsers] = useState<User[]>([]);
const [error, setError] = useState("");
async function onUserSearch(username: string) {
try {
const users = await githubUsersProvider.getUsers(username);
setUsers(users);
} catch (e) {
setUsers([]);
setError(
"There was an error retrieving the data: " + (e as Error).message
);
}
}
function onSearch() {
console.log('reached before setTimeout') // gets excuted
let timeoutId = setTimeout(() => {
if (queryUser !== "") {
onUserSearch(queryUser);
}
}, 500);
return () => clearTimeout(timeoutId);
}
console.log(queryUser);
return (
<div className="app">
{error && <div className="error-message">{error}</div>}
{!error && (
<div className="app-content">
<h1>Github Repository Explorer</h1>
<div className="input-container">
<input
type="text"
placeholder="Enter a username..."
value={queryUser}
onChange={(e) => setQueryUser(e.target.value)}
/>
<button onClick={() => onSearch()}>Search</button>
</div>
<main className="user-main">
{users.map((user) => {
return (
<DisplayUser
username={user.username}
profileUrl={user.profileUrl}
/>
);
})}
</main>
</div>
)}
</div>
);
}
export default App;
Elias Rey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.