Skip to content
Eliseo Geraldo edited this page May 23, 2019 · 6 revisions

📬 state

Consume state

It can be consumed directly from store, without props or Component.state intervention, just need create a store before and...

import store from './store'

class MyComponent {
  render () {
    return (
      <Text>
        { store.state.property }
      </Text>
    )
  }
}

Update state setState

state can be updated from actions (recomended), or using a simple setState method (we can use ss method too, it's a shorthand for setState), WARNING in different with React Component.setState wallant method is synchronous, that means you can update state and use it immediately after that. Ex:

// ss === setState => true
state = {
  count: 0
}

[store|Component].setState({
  count: count + 1
})

console.log(store.state.count === 1)
// true <- Wallant
// false <- React component

state can be updated with a callback too, this results specially confortable because you can make complex transformations, callback gets a copy of state, and need return the new state Ex:

using ss instead setState

store.ss(state => {

  state.users = state.users
    .filter(user => user.name.startsWith('a'))
    .sort((user, nextUser) => user.name - nextUser.name)

  state.message = (state.users.length > 10)
    ? 'More than 10 users in store'
    : 'Less than 10 users in store'

  return state
})

It's recomendable update state using actions

Clone this wiki locally