Skip to content

Commit

Permalink
Add ViewStore.binding migration examples to guide (#3087)
Browse files Browse the repository at this point in the history
* Add `ViewStore.binding` migration examples to guide

The 1.7 guide doesn't have examples of more complex bindings, so let's
add one.

* fix

* wip

* fix
  • Loading branch information
stephencelis committed May 14, 2024
1 parent a7daa9f commit 57526d8
Showing 1 changed file with 49 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,55 @@ TabView(selection: $store.tab.sending(\.tabChanged)) {
}
```

If the binding depends on more complex business logic, you can define a custom `get`-`set` property
(or subscript, if this logic depends on external state) on the store to incorporate this logic. For
example:

@Row {
@Column {
```swift
// Before

// In the view:
ForEach(Flag.allCases) { flag in
Toggle(
flag.description,
isOn: viewStore.binding(
get: { $0.featureFlags.contains(flag) }
send: { .flagToggled(flag, isOn: $0) }
)
)
}
```
}
@Column {
```swift
// After

// In the file:
extension StoreOf<Feature> {
subscript(hasFeatureFlag flag: Flag) -> Bool {
get { featureFlags.contains(flag) }
set {
send(.flagToggled(flag, isOn: newValue))
}
}
}

// In the view:
ForEach(Flag.allCases) { flag in
Toggle(
flag.description,
isOn: $store[hasFeatureFlag: flag]
)
}
```
}
}

> Tip: When possible, consider moving complex binding logic into the reducer so that it can be more
> easily tested.
## Computed view state

If you are using the `ViewState` pattern in your application, then you may be computing values
Expand Down

0 comments on commit 57526d8

Please sign in to comment.