1.0.0 • Published 3 years ago

@mng12345/m-state v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

use hooks and closure to make a state manager

1. change react state

2. change the state anywhere

3. get current state value

example

const husband = atom({
  defaultValue: {
    name: 'zm',
    age: 27
  },
  key: 'husband'
})

const wife = atom({
  defaultValue: {
    name: 'zl',
    age: 28
  },
  key: 'wife'
})

const AllAge = () => {
  const [husbandState, setHusband] = useMState(husband)
  const [wifeState, setWife] = useMState(wife)
  return (
    <>
      allAge: {husbandState.age + wifeState.age}<hr/>
      <button onClick={() => {
        setHusband({
          ...husbandState,
          age: husbandState.age + 1
        })
        setWife({
          ...wifeState,
          age: wifeState.age + 1
        })
      }}>
      addAllAge
      </button>
  </>
)
}

const App = (): JSX.Element => {

  const [husbandState, setHusband] = useMState(husband)
  const [wifeState, setWife] = useMState(wife)
  const addHusbandAge = () => {
    setHusband({
      ...husbandState,
      age: husbandState.age + 1
    })
  }
  const addWifeAge = () => {
    setWife({
      ...wifeState,
      age: wifeState.age + 1
    })
  }

  return (
    <div>
      husband: {husbandState.name}<hr/>
      wife: {wifeState.name}<hr/>
      husband age: {husbandState.age}<hr/>
      wife age: {wifeState.age}<hr/>
      <button onClick={addHusbandAge} style={{
        marginRight: 10
      }}>addHusbandAge</button>
      <button onClick={addWifeAge}>addWifeAge</button>
      <hr/>
      <AllAge />
    </div>
    )
}

render(<App />, document.getElementById('app'))