UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Passing view state to parent ObservationalObject

Forums > SwiftUI

I have a view containing a list view and an input field. I want a change in the input field to recall my API with the search field value. My approach was to pass through searchText into inputQuery in the declaration of the observed object Fetcher, but this wouldn't work in the initialiser.

I'm quite new to SwiftUI and I've spent hours looking for how to do this but can't work it out so any help would be much appreciated.

Here is the main View


struct FetchView: View {
@State private var searchText = ""
@ObservedObject var fetcher = SneakerFetcher(inputQuery:"") //Cant pass in SearchText state here

var body: some View {
VStack {
Spacer()
SearchBar(text: $searchText)
Text(searchText)

List(fetcher.shoes) { shoe in
VStack (alignment: .leading) {
HStack {
WebImage(url: URL(string: shoe.ImageURLs.imageUrl ?? "https://stockx.imgix.net/Air-Jordan-XXX1-Air-Jordan-Brand-Classic-East-Product.jpg?fit=fill&bg=FFFFFF&w=700&h=500&auto=format,compress&trim=color&q=90&dpr=2&updated_at=1598377218"))
.resizable()
.frame(width: 70, height: 50)

Text(shoe.name)
.font(.system(size: 11))
.foregroundColor(Color.black)
}}
}.listStyle(PlainListStyle()) // removes weird padding
}}}

Here's the ObservableObject that calls the API

 func load() {
        let url = URL(string: "https://api.thesneakerdatabase.com/v1/sneakers?limit=10&name=\(inputQuery)")!

        URLSession.shared.dataTask(with: url) {(data,response,error) in
            do {
                if let d = data {

                    let result = try JSONDecoder().decode(APIResponse.self, from: d)
                    DispatchQueue.main.async {
                        self.shoes = result.results //push results data to shoes struct
                        print(result.results)
                    }
                }else {
                    print("No Data")
                }
            } catch {
                print("Error info: \(error)")
            }

        }.resume()

    }
}

2      

Use an onChange handler to observe searchText and then update fetcher.inputQuery and call its load() function.

Soemthing similar to this:

.onChange(of: searchText) { _ in
    fetcher.inputQuery = searchText
    fetcher.load()
}

3      

@roosterboy Perfect! Thanks a lot

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.