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

Load data on a view and pass Id to load different data on another view

Forums > SwiftUI

Hi, I want to load a list of items in one view then pass an item's Id and use it to fetch other data in another view. What's the best approach to do so. Here is what I have so far but I m stuck in using the id in the second view (PostView.swift).

PostsListView
struct PostsListView: View {
    @ObservedObject var obs = postsObserver()
    var body: some View {
        NavigationView{
            ScrollView(){
                VStack{
                    ForEach(obs.posts, id: \.name) {post in
                        NavigationLink(destination: PostView(postId: post.id)){
                            VStack(alignment: .leading){
                                Text(post.name)
                            }
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                }.padding(.horizontal)
            }.id(UUID().uuidString)
        }
    }
}
class postsObserver: ObservableObject{
    @Published var posts = [Post]()

    init() {
        AF.request("http://localhost/posts").responseData{(data) in
            let json = try! JSON(data: data.data!)
            for i in json {
                self.posts.append(
                    Post(
                        id: i.1["id"].intValue,
                        name: i.1["name"].stringValue,
                    )
                )
            }
        }
    }
}

// PostView.swift
struct PostView: View {
    @State var postId: Int
    @ObservedObject var obs = postObserver()

    var body: some View {
        VStack {
            Text("\(obs.specificValue)")
            Text("\(postId)")
        }
    }
}

class postObserver: ObservableObject{
 //   @Published var post = Post
 //   AF.request("http://localhost/posts/\(postId)").responseData{(data) in
}

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.