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

SOLVED: SwiftUI data flow: how to update existing objects?

Forums > SwiftUI

Let's say I'm building app for viewing and editing posts. Here's my model for Post and app itself:

struct Post: Hashable {
    var id: Int
    var title: String
}

class Store: ObservableObject {
    // 
    // In real-life this should be fetched via API on app/view start
    //
    @Published var items: [Post] = [
        Post(id: 1, title: "Foo"),
        Post(id: 2, title: "Bar"),
        Post(id: 3, title: "baz"),
    ]
}

@main
struct PlaygoundApp: App {
    @StateObject var store = Store()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(store)
        }
    }
}

And here's the list with all posts. I can navigate to each post's own view and edit post data (usually via API):

struct ContentView: View {
    @EnvironmentObject var store: Store

    var body: some View {
        NavigationView {
            List {
                ForEach(store.items, id: \.self) { post in
                    NavigationLink(destination: PostView(post: post).navigationTitle(post.title)) {
                        Text(post.title)
                    }
                }
            }
        }
    }
}

struct PostView: View {
    var post: Post

    var body: some View {
        Text(post.title)
        Button(action: {
            //
            // Make API call and edit Post title
            /// THIS WILL NOT COMPILE
            // post.title = "New title"
            // 
        }, label: {
            Text("Edit title")
        })
    }
}

So if I try to edit post (directly or after API call, it doen't matter), I:

  1. can't assign new value to existing var post: Post struct from post itself
  2. cant trigger view to be re-rendered

What is the correnct approach to reflect data changes in existing Observable storage? I thought of two ways to fix it:

  1. make method like store.fetch_posts() and call it after pressing button, but this will trigger to re-render all post view and reset scrolling position, and likely it will not work at all as expected
  2. in Ios15 there's abillity to iterate over bindings (https://www.swiftbysundell.com/articles/bindable-swiftui-list-elements/). I thought this might be a solution, but there should be existing way to handle such a generic usecase

Thank you

2      

Solved:

  1. Make post ObservedObject;
  2. Make Post class instead of struct.

2      

hi,

before turning a Post into a class and adding @ObservedObject references ... SwiftUI really likes structs ... i'd suggest that you pick out the Store object from the environment of the PostView (or pass it in as an argument), and when you want to make an edit to the post, "tell the Store to make the edit for you" with some method, e.g., store.updateTitle(for: post, to: newTitle).

then the Store simply does something like:

func updateTitle(for post: Post, to newTitle: String) {
  if let index = items.firstIndex(where: { $0.id == post.id }) {
    items[index].title = newTitle
  }
}

that's it: everything should get redrawn.

hope that helps,

DMG

3      

Thank you! Turned back to Struct because with Class I've got very strange bugs with non-updating views due to its mutating nature.

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.