Skip to content

Instantly share code, notes, and snippets.

@oliverfoggin
Created August 5, 2021 19:38
Show Gist options
  • Save oliverfoggin/d893197441718aa44eb5d504df1bcd07 to your computer and use it in GitHub Desktop.
Save oliverfoggin/d893197441718aa44eb5d504df1bcd07 to your computer and use it in GitHub Desktop.
import SwiftUI
import ComposableArchitecture
struct SearchableState: Equatable {
var searchText = ""
var names = ["Oliver", "Emily", "Jessica", "Dan", "Eva"]
var searchResults: [String] {
if searchText.isEmpty {
return names
} else {
return names.filter { $0.lowercased().contains(searchText.lowercased()) }
}
}
var isSearching = false
var sectionTitle: String {
self.isSearching ? "Searching" : "Not Searching"
}
}
enum SearchableAction {
case binding(BindingAction<SearchableState>)
}
struct SearchableEnvironment {}
let searchableReducer = Reducer<SearchableState, SearchableAction, SearchableEnvironment> { _, _, _ in .none }
.binding(action: /SearchableAction.binding)
struct SearchableView: View {
let store: Store<SearchableState, SearchableAction>
var body: some View {
WithViewStore(self.store) { viewStore in
NavigationView {
SearchableList(store: self.store)
.navigationBarTitle("Searchable")
.searchable(
text: viewStore.binding(keyPath: \.searchText, send: SearchableAction.binding),
prompt: "Search names..."
)
}
}
}
}
struct SearchableList: View {
let store: Store<SearchableState, SearchableAction>
@Environment(\.isSearching) var isSearching
var body: some View {
WithViewStore(self.store) { viewStore in
List {
Section(viewStore.sectionTitle) {
ForEach(viewStore.searchResults, id: \.self) { name in
Text(name)
}
}
}
.onChange(of: isSearching) { newValue in
viewStore.send(.binding(.set(\.isSearching, newValue)))
}
}
}
}
struct SearchableView_Previews: PreviewProvider {
static var previews: some View {
SearchableView(
store: Store(
initialState: .init(),
reducer: searchableReducer,
environment: .init()
)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment