Object Is Not Iterable Error While Using React-context
So I recently started using React and am learning the Context Api. The zest of my code is: export const UsersContext = createContext(); export function UsersProvider(props) { c
Solution 1:
You're using useContext
outside of the provider, you should use useContext
in a child component.
import { UsersContext, UsersProvider } from'./UsersContext';
exportdefaultfunctionUsersPage() {
const [users, setUsers] = useContext(UsersContext);
return (
<UsersProvider>
{users.map(function (user) {
<divkey={user.id}>{user.id}</div>
})}
</UsersProvider>
);
}
is the same as
import { UsersContext, UsersProvider } from'./UsersContext';
exportdefaultfunctionUsersPage() {
return (
<UsersContext.Consumer>
{([users, setUsers]) => (
<UsersProvider>
{users.map(function(user) {
<divkey={user.id}>{user.id}</div>;
})}
</UsersProvider>
)}
</UsersContext.Consumer>
);
}
as you can see the consumer is not a child of the provider, thus there is nothing provided to it. Consuming it in a child component works.
import { UsersContext, UsersProvider } from'./UsersContext';
exportdefaultfunctionUsersPage() {
return (
<UsersProvider><UsersPageChild /></UsersProvider>
);
}
functionUsersPageChild() {
const [users, setUsers] = useContext(UsersContext);
return (
<div>
{users.map(function(user) {
<divkey={user.id}>{user.id}</div>;
})}
</div>
);
}
Post a Comment for "Object Is Not Iterable Error While Using React-context"