Albert
Albert

Reputation: 99

Move .onChange() to its own place so I don't repeat it so many times

I hate repeating code and I'm currently doing it, how can I put the snippet below into another... view? so that I can call it instead of writing all that? The reason why I have all that logic in a view instead of a viewmodel is because of environment state:

.onChange(of: walletDataStoreHandlerViewModel.walletsReceivedNewValue) { newValue in
    if(walletDataStoreHandlerViewModel.reloadingWallets == false) {
        walletDataStoreHandlerViewModel.reloadingWallets = true
        print("🟢 Reloading wallet....")
        
        Task {
            try await walletDataStoreHandlerViewModel.getUserWallets(user: user)
        }
    }
}

Upvotes: 0

Views: 171

Answers (2)

user12395631
user12395631

Reputation:

Though the answer provided works, It does emphasize that it is a fast idea. That being said, you should probably not have your logic in the view, rather move it into a ViewModel. Refactoring your code will help you long term, especially if this is a project that you want to scale.

This can help: https://www.swiftyplace.com/blog/swiftui-and-mvvm

Upvotes: 1

Hrabovskyi Oleksandr
Hrabovskyi Oleksandr

Reputation: 3275

First fast idea how to decrease the amount of code: create a separate ViewModifier:

struct WalletUpdater: ViewModifier {

   let walletVM: YourWalletVMType

   func body(content: Content) -> some View {
      content
         .onChange(of: walletVM.walletsReceivedNewValue) { newValue in
            // your code of updating
         }
   }
}

The example of usage:

//..
VStack {
   // something
}
.modifier(WalletUpdater(walletVM: walletDataStoreHandlerViewModel)

P.S. Additionally you can create a View extension

Upvotes: 1

Related Questions