Transitioning from JavaScript to TypeScript while learning React has presented me with a new challenge.
The initial state for my context is blank, which is causing issues with accessing the properties.
If you prefer, here is the repository link: https://github.com/lets-c-whats/ts-github-finder/blob/main/src/components/users/UserResults.tsx
Context file
const GithubContext = createContext({});
interface GithubContextProps {
children: React.ReactNode;
}
export const GithubProvider = ({ children }: GithubContextProps) => {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const fetchUsers = async () => {
const response = await fetch(`${GITHUB_URL}/users`, {
headers: {
Authorization: `token ${GITHUB_TOKEN}`,
},
});
const data = await response.json();
setUsers(data);
setLoading(false);
};
return (
<GithubContext.Provider
value={{
users,
loading,
fetchUsers
}}
>
{children}
</GithubContext.Provider>
);
};
export default GithubContext;
I have wrapped the App with the provider, and within the Home component is UserResults component
import { GithubProvider } from "./context/github/githubContext";
...
function App() {
return (
<GithubProvider>
...
<Route path="/" element={<Home />} />
</GithubProvider>
);
}
After that, I am trying to access the values inside the component using the useContext hook
// DEPENDENCIES
import { useEffect, useContext } from "react";
import GithubContext from "../../context/github/githubContext";
function UserResults() {
const {users, loading, fetchUsers} = useContext(GithubContext)
useEffect(() => {
fetchUsers()
})
if (!loading) {
return (
<div className="grid grid-cols-1 gap-8 xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2">
{users.map((user) =>) {
return <UserItem key={user.id} userData={user} />;
})}
</div>
);
} else {
return <Spinner />
}
}
export default UserResults;
Even after all this effort, the app isn't functioning correctly, as it throws these errors:
TS2339: Property 'users' does not exist on type '{}'.
8 |
9 | function UserResults() {
> 10 | const {users, loading, fetchUsers} = useContext(GithubContext)
| ^^^^^
ERROR in src/components/users/UserResults.tsx:10:17
TS2339: Property 'loading' does not exist on type '{}'.
8 |
9 | function UserResults() {
> 10 | const {users, loading, fetchUsers} = useContext(GithubContext)
| ^^^^^^^
ERROR in src/components/users/UserResults.tsx:10:26
TS2339: Property 'fetchUsers' does not exist on type '{}'.
8 |
9 | function UserResults() {
> 10 | const {users, loading, fetchUsers} = useContext(GithubContext)
| ^^^^^^^^^^
ERROR in src/components/users/UserResults.tsx:19:21
TS7006: Parameter 'user' implicitly has an 'any' type.
17 | return (
18 | <div className="grid grid-cols-1 gap-8 xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2">
> 19 | {users.map((user) => {
| ^^^^