README
@watch-state/react
State manager of React 16.8+ based on watch-state
Install
npm
npm i @watch-state/react
yarn
yarn add @watch-state/react
Usage
Class Component
You can use class components.
import React, { Component } from 'react'
import watch, { state } from '@watch-state/react'
@watch
class UserName extends Component {
@state name = 'Mike'
render () {
return (
<input
value={this.name}
onChange={e => this.name = e.target.value}
/>
)
}
}
Function Component
You can use function components.
import React from 'react'
import { useWatch } from '@watch-state/react'
const $show = new State(false)
const AsideMenuButton = () => {
const toggle = () => $show.value = !$show.value
return <button onClick={toggle} />
}
const AsideMenu = () => {
const show = useWatch($show)
return show ? (
<div>Aside Menu</div>
) : null
}
Cache
Use cache
when you want to cache computed values.
import React, {Component} from 'react'
import watch, {getState, state, cache} from '@watch-state/react'
class Core {
@state items = []
@cache get sortedItems () {
return [...this.items].sort()
}
addItem (item) {
this.items.push(item)
getState(this, 'items').update()
}
}
const core = new Core()
@watch
class Items extends Component {
render () {
return core.sortedItems.map(todo => (
<div key={todo}>{todo}</div>
))
}
}
Mixer
Use mixer on computed values related to props
import React, {Component} from 'react'
import watch, {State, mixer} from '@watch-state/react'
interface UserProps {
id?: number
}
const prefix = new State('Id: ')
@watch
class User extends Component<UserProps> {
@mixer get info () {
return prefix.value + this.props.id
}
render () {
return this.info
}
}
Event
Use event
if you want to change several states in one action.
import React, {Component} from 'react'
import watch, {state, event} from '@watch-state/react'
@watch
class Test extends Component {
@state field1 = 'value1'
@state field2 = 'value2'
@event setFields () {
this.field1 = 'new value1'
this.field2 = 'new value2'
}
render () {
return (
<button onclick={() => this.setFields()}>
field1: {this.field1}, field2: {this.field2}
</button>
)
}
}
Links
Issues
If you find a bug or have a suggestion, please file an issue on GitHub