0

I have this code inside which I'm calling "makeView" function that returns a View, and in the makeView function I'm incrementing the variable "id" and passing it to the View, but when I do this it shows this error

"Updating a preview from SongsList_Previews in SongBook.app (2935) took more than 5 seconds."

And surprisingly when I comment out the line "self.id += 1" everything works. I'm new to SwiftUI, so forgive me if I left out some information.

struct SongsList: View {
    @State private var id: Int = 0
    var body: some View {
        
        VStack{
            NavigationView {
            List(songs) {
                song in NavigationLink(
                    destination: SongMainView(song: song)) {
                        makeView(song: song)
                    }
            }
        }
    }
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .leading)
        .background(Color.orange.opacity(0.2))
        .edgesIgnoringSafeArea(.all)
    }
    
    func makeView(song: Song) -> SongsIndexView {
        self.id += 1;
        return SongsIndexView(song: song, id: self.id)
    }
}
sharpnife
  • 198
  • 12

1 Answers1

1

The variable is marked with @State property wrapper.

@State private var id: Int = 0

Every time this value changes, SwiftUI tries to update the view.

func makeView(song: Song) -> SongsIndexView {
    self.id += 1;
    return SongsIndexView(song: song, id: self.id)
}

This causes an infinite loop like -

  1. id = 1, updateView (but now id = 2 because of id += 1)
  2. id = 2, updateView (but now id = 3 because of id += 1)

You should never mutate the state while view is being updated.

Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30
  • Hi, so what's the alternative? I want to increment the "id" variable each time makeView is called and I want to pass it to the SongsIndexView. – sharpnife Jun 15 '21 at 08:41
  • Remove the `@State private var id: Int = 0` declaration. Pass the index from outside like `makeView(song: Song, index: Int) -> SongsIndexView`. – Tarun Tyagi Jun 15 '21 at 08:43