Skip to content

Add custom hook for context to avoid assertions #604

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 13, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1529,11 +1529,19 @@ export const App = () => (
<AppCtx.Provider value={sampleAppContext}>...</AppCtx.Provider>
);

const useAppContext = () => {
const appContext = useContext(AppCtx);
if (!appContext) {
throw new Error("useApp must be used within <AppCtx.Provider>.");
}
return appContext;
};

// Consume in your app
import { useContext } from "react";

export const PostInfo = () => {
const appContext = useContext(AppCtx);
const appContext = useAppContext();
return (
<div>
Name: {appContext.name}, Author: {appContext.author}, Url:{" "}
Expand Down
10 changes: 9 additions & 1 deletion docs/basic/getting-started/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,19 @@ export const App = () => (
<AppCtx.Provider value={sampleAppContext}>...</AppCtx.Provider>
);

const useAppContext = () => {
const appContext = useContext(AppCtx);
if (!appContext) {
throw new Error("useApp must be used within <AppCtx.Provider>.");
}
return appContext;
};

// Consume in your app
import { useContext } from "react";

export const PostInfo = () => {
const appContext = useContext(AppCtx);
const appContext = useAppContext();
return (
<div>
Name: {appContext.name}, Author: {appContext.author}, Url:{" "}
Expand Down