-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
Context provider can't be found #3044
Comments
The way Hooks work comes with one strong caveat by design, and that is that they must called consistently when a component renders. What's happening here is that this contract is broken in the function toggleFeature(feature) {
const ctx = useContext(AppContext);
ctx.toggleFeature(feature);
}
function Header(props) {
return html`<header>
<button
onClick="${() => {
toggleFeature(props.feature);
}}"
>
enable/disable
</button>
</header>`;
} Notice that the function Header(props) {
return html`<header>
<button
onClick="${() => {
// BAD: Hook is not part of the component's render phase
const ctx = useContext(AppContext);
ctx.toggleFeature(props.feature);
}}"
>
enable/disable
</button>
</header>`;
} To fix our broken contract we need to ensure that the function Header(props) {
// GOOD: Hooks should be called here
const ctx = useContext(AppContext);
return html`<header>
<button
onClick="${() => ctx.toggleFeature(props.feature)}"
>
enable/disable
</button>
</header>`;
} And voilà, changing settings work as expected 👍 |
Oh my god, thank you so much! 💖 I knew it was going to be just a simple answer of "yeah you're doing it wrong". This makes complete sense (and I even did it this way in another component too, silly me). Thanks for the quick response! |
Explanation: preactjs/preact#3044
Reproduction
I haven't been able to create a contained reproducible example but it does happen to other people on different browsers. This used to work when I first wrote it but at some point an update somewhere must have broken it. I've tried looking at it and through the Preact documentation but as I'm pretty inexperienced with Preact I can't figure out what I'm doing wrong.
You can either build the project from source (
yarn watch
in one terminal andyarn start:firefox
/yarn start:chromium
in another) or install the extension from Mozilla Addons.Steps to reproduce
In the extension page (click on the extension icon to go there) enabling or disabling a feature in the setting header does not work.
Expected Behavior
The feature should get toggled.
Actual Behavior
Preact errors out saying it can't find the provider.
The error message
Explanation of my code
Creating the context
Link to code.
Creating the state
Link to code.
Creating the context provider
Link to code.
The component that fails
Link to code.
Creating the component
Link to code.
The text was updated successfully, but these errors were encountered: