WWDC21 SALE: Save 50% on all my Swift books and bundles! >>

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()

    }
}

   

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()
}

1      

@roosterboy Perfect! Thanks a lot

   

Save money with our WWDC sale!

SAVE 50% To celebrate WWDC21, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

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.