Issue
I created context with null initial value that I am now accessing in other component. However when I destructure it to access the variables form the context then I get ts error:
Property 'users' does not exist on type 'GithubContextProps
function UserResults() {
const appContext = useContext(GithubContext)
const { users, loading, fetchUsers } = appContext
useEffect(() => {
fetchUsers()
}, [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 : User) => (
<UserItem key={user.id} user={user} />
))}
</div>
)
} else {
return <Spinner />
}
}
And here is where i created context:
export type User = {
id: number;
login: string;
avatar_url: string;
}
interface GithubContextProps {
users: User[];
loading: boolean;
fetchUsers: () => void;
}
const GithubContext = createContext<GithubContextProps | null>(null)
I tried solving this with using conditional checking whether appContext
is not null but then useEffect will throw errors that it cannot be used conditionally in this component. Any idea how to solve it without resorting to turning off React strict mode?
Solution
How about:
const { users, loading, fetchUsers } = appContext ?? {};
You'll get undefined
when appContext is null
.
Answered By - Jakub Binkowski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.