How to fetch data from API in SwiftUI views?

You can fetch immediately when you initialise view model’s init, you can trigger via button in your view. or like there is onAppear {} you can use in your view.

struct VideoListView: View {

    @ObservedObject private var viewModel = VideoViewModel()

    var body: some View {
        VStack {
            Button(action: {
                self.viewModel.fetchVideos()
            }) {
                Text("Fetch Videos")
            }
        }.onAppear {
            self.viewModel.fetchVideos()
        }
    }
}

Hope it helps.