arnelenero / simpler-state

The simplest app state management for React
https://simpler-state.js.org
MIT License
478 stars 16 forks source link

Class based component example and re-render #13

Closed synapse closed 1 year ago

synapse commented 3 years ago

Hey there, very nice library. Super easy to set up and ready to be used. My question is since I still have a mixed function and calss based components, if is there a way to trigger a re-render when the store is update?

arnelenero commented 3 years ago

Hi. Since simpler-state's API was primarily designed to be used with Hooks, the class-based support has remained undocumented. But if you're not using TypeScript, there is one method on the entity that you can use, something like this: inside your class-based component:

In an initializer function:

// Subscribe to the counter entity
this.unsubscribeFromCounter = counter._subscribe(newValue => {
  if (this.state.counter !== newValue) 
    this.setState({ counter: newValue })
})

In a cleanup function:

  this.unsubscribeFromCounter()

This is a "private" method at the moment (make sure not to omit the underscore prefix), and so if you're using TypeScript the compiler will complain. But since there seems to be use-cases involving a combination of function-based and class-based components, I am considering exposing subscribe as a public method.

synapse commented 3 years ago

Thanks, @arnelenero that would work. I'll have to make an interface since I'm using TS. But in the meanwhile, I found out that I could also create a function-based component and wrap my main component passing down the store as props. Anyways keep up the good works. Seams nice to use

arnelenero commented 3 years ago

Thanks, @arnelenero that would work. I'll have to make an interface since I'm using TS. But in the meanwhile, I found out that I could also create a function-based component and wrap my main component passing down the store as props.

Good point, that would be the quickest workaround indeed, especially if you're using TS.