Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider adding updateState convenience method #27

Closed
jconst opened this issue Oct 19, 2016 · 0 comments
Closed

Consider adding updateState convenience method #27

jconst opened this issue Oct 19, 2016 · 0 comments

Comments

@jconst
Copy link
Contributor

jconst commented Oct 19, 2016

React provides the setState method which allows easily setting a subset, or all, of a component's state and triggering a render. Similarly, Few.swift provides the updateState function (but unfortunately does not make it easy to set just a piece of the state object). These functions, while simple, are valuable because they encourage a certain paradigm.

I personally use the following:

class Ref<T> {
  var value: T

  init(_ value: T) {
    self.value = value
  }
}

extension ComponentViewType {
  func updateState<T: ComponentStateType>(@noescape block: (Ref<T?>) -> ()) {
    let castedState = state as? T
    let reference = Ref(castedState)
    block(reference)
    state = reference.value
    renderComponent(CGSize.undefined)
  }
}

So then updateState can then be called like so:

struct BookState: ComponentStateType {
  var title: String
  var author: String
}

// then in a button callback or something:
updateState{ (state: Ref<BookState?>) in
  state.value!.title = "new title"
}

as opposed to currently needing to write:

var newState = myState!
newState.node = node
state = newState
renderComponent()

The (state: Ref<BookState?>) is necessary because the infra doesn't know what your ComponentStateType subclass is, but this can be solved if the state type is made a generic parameter of the view type, as Few.swift does.

If you think this seems reasonable I'd be happy to open a pull request! Interested to hear your thoughts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants