Skip to content

Conversation

@buzsh
Copy link
Contributor

@buzsh buzsh commented Jun 9, 2024

  1. Declare in React view:
const [switchValue, setSwitchValue] = useExposeState<boolean>(true, 'switchValue');
  1. Use SwiftGen

  2. Connect in SwiftUI view:

let manager: ObservableWebViewManager
@State private var switchValue: Bool = true
ObservableWebView(manager: manager)
  // change happened in React side
  .tsMessageHandler(.switchValue {  newValue in
    switchValue = newValue // update Swift var
  }, manager: manager)
  // change happened on Swift side
  .onChange(of: switchValue) {
    manager.ts(.switchValue(switchValue)) // update React var
  }

Next Steps

Modifiers

ObservableWebView(manager: manager)
  .sync(.switchValue, $switchValue, manager: manager)

Observable Classes

SwiftGen generates one State variable.

  • Updating it from Swift will automatically update the React variable
  • Updating it from React will automatically update the Swift variable
@Observable
class Variables {
  init(manager: WKWebView) { ... }
 
  let webView: WKWebView
  var switchValue: TypeSwiftObservable {
    get: // retrieve from React
    set: // set in React
  }

  func render() {
    withObservationTracking {
      for variable in TypeSwift.Variables {
        // case .switchValue: self.switchValue = switchValue
      }
    } onChange: {
      render()
    }
  }
}

Usage

.onChange(of: switchValue) {
  // do something
}

Observable Environments

Usage

@Environment(\.variable) private var variable

variable.switchValue  // call directly
variable.$switchValue // edit directly

Copy link
Contributor Author

@buzsh buzsh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In review.

Copy link
Contributor Author

@buzsh buzsh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved.

@buzsh buzsh merged commit c50e4b2 into main Jun 9, 2024
@buzsh buzsh deleted the synchronous-bidirectional-variable branch June 9, 2024 20:22
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

Successfully merging this pull request may close these issues.

2 participants