Valtio with class components #69
-
Could I use Valtio with React class based components? There are no examples, but I think it should work because of the subscribe and unsubscribe feature....? An example would be much appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Well, useProxy is only for function components. |
Beta Was this translation helpful? Give feedback.
-
Perhaps this solution would be useful if you use a context provider, and don't want to wrap your component in a HOC, but want to use only classes: I // Reusable class - similar to `useSnapshot`
class ComponentThatReadsMyTypeFromContext extends Component {
componentDidMount() {
// Subscribe here and in componentDidUpdate if the context value changed
this.unsubscribeFromContext = subscribe(this.context, () => {
// Will happen if the context value changes or if the proxy changes
this.forceUpdate();
});
}
get myType(): MyType {
return snapshot(this.context);
}
}
// Used in various components
class MyComponent extends ComponentThatReadsMyTypeFromContext {
render() {
// Use a snapshot to read
return <div onClick={this.onClick}>{this.myType.foo}</div>
}
onClick = () => {
// Use the proxy the write
this.context.foo = "baz";
}
} I've included a full example here https://codesandbox.io/s/sharp-cannon-5j2kv9?file=/src/MyComponent.tsx It should be similar if you want to just subscribe to a instance value, rather than a context provider, but the solution would be more generic. I think it'd be valuable for Valtio to consider class-based codebases as well, and provide either such a class, or some documentation |
Beta Was this translation helpful? Give feedback.
Well, useProxy is only for function components.
It would be too tricky (or too much effort) to directly subscribe from class components.
I'd recommend wrapping a class component with a function component and useProxy.
It would be worth trying, and I'd encourage you to create such an example. 💪