Skip to content
This repository has been archived by the owner on Jun 23, 2024. It is now read-only.

Unexpected behaviour when Providing state #12

Closed
bradlc opened this issue Jul 26, 2018 · 8 comments
Closed

Unexpected behaviour when Providing state #12

bradlc opened this issue Jul 26, 2018 · 8 comments

Comments

@bradlc
Copy link

bradlc commented Jul 26, 2018

Hi. I’m trying to update context from a nested component, similar to this example in the React docs.

However, preact-context doesn’t behave as expected (and as React.createContext does).

Here’s an example:
preact-context: https://codesandbox.io/s/q3n91mr3nw
React.createContext: https://codesandbox.io/s/nrpx565z50

@valotas
Copy link
Owner

valotas commented Jul 26, 2018 via email

@bradlc
Copy link
Author

bradlc commented Jul 27, 2018

Hey George,

Sounds good, thanks! 😎

Had a quick look, and if I change the Consumer component's shouldComponentUpdate method to just return true; it works as expected. So maybe it's an issue with the condition here?:

return (
this.state.value !== nextState.value ||
getRenderer(this.props) !== getRenderer(nextProps)
);

@bradlc
Copy link
Author

bradlc commented Jul 27, 2018

Actually, although changing it to return true; fixes the test case above, it doesn’t fix the original issue that I’m having on a project (again, it works fine with React.createContext). I will create another reduced test case for that if I can.

Edit: the issue on my project was actually caused by this preact bug, so you can disregard this comment

@valotas
Copy link
Owner

valotas commented Jul 29, 2018

@bradlc the problem is that preact mutates the state instance on each update hence the this.state.value !== nextState.value check is always true. You have to make sure that you pass a new instance of the value to the Context.Provider (ex: <Context.Provider value={{ ...this.state }}>, see your updated example).

@valotas
Copy link
Owner

valotas commented Jul 29, 2018

I'll try to catch up with some of the preact maintainers in order to provide a proper solution for that as it looks like it will be a problem that many preact users might have.

@marvinhagemeister
Copy link

marvinhagemeister commented Aug 19, 2018

This issue is caused by using an older release of preact. With the most recent version 8.3.1 I can't reproduce the issue anymore and the example works exactly the same as for react.

@bradlc
Copy link
Author

bradlc commented Aug 19, 2018

You’re right, updating the CodeSandbox to 8.3.1 fixes the issue. Thanks!

@bradlc bradlc closed this as completed Aug 19, 2018
@valotas
Copy link
Owner

valotas commented Aug 21, 2018

thanks a lot for the clarification @marvinhagemeister !

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants