I am enjoying round with MVVM and have bother wrapping my head round the way to work with deciding on a single component.
Following on-line examples I’ve written one thing primary that fetches an inventory of information and shows it.
struct NoteListView: View {
@State personal var mannequin = NoteModel()
var physique: some View {
NavigationStack {
Checklist(mannequin.notes) { word in
NavigationLink {
NoteDetailView(word: word)
} label: {
Textual content(word.title)
}
}
.job {
mannequin.fetchNotes()
}
}
}
}
struct NoteDetailView: View {
let word: Notice
var physique: some View {
Textual content(word.title)
.font(.title)
Textual content(word.content material)
}
}
@Observable
class NoteModel {
var notes: [Note] = []
func fetchNotes() {
self.notes = [
Note(title: "First note", content: "Test note"),
Note(title: "Reminder", content: "Don't forget to water the plants!"),
Note(title: "Shopping list", content: "Eggs, milk, hat, bread")
]
}
}
struct Notice: Identifiable, Hashable {
let id = UUID()
var title: String
var content material: String
}
Now I wish to replace a word on the element view. Updating entails a PUT request to the server with the server calculating knowledge for the replace, so after the request is profitable the brand new model of the word must be fetched. I am unable to appear to determine the way to write this. I feel the mannequin would look one thing like this.
@Observable
class NoteModel {
var notes: [Note] = []
var selectedNote: Notice?
func fetchNotes() {
self.notes = [
Note(title: "First note", content: "Test note"),
Note(title: "Reminder", content: "Don't forget to water the plants!"),
Note(title: "Shopping list", content: "Eggs, milk, hat, bread")
]
}
func fetchNote(title: String) {
// fetch a single word, in all probability used after updating a word to show the up to date word on the small print view
self.selectedNote = APIClient.fetchNote()
}
func updateNote(title: String, content material: String) {
self.selectedNote?.title = title
self.selectedNote?.content material = content material
// makes a PUT request to replace the word, after which the word must be fetched
}
}
However I do not know the way to cross the chosen word to the small print view and the way to replace the word displayed on the small print view and on the checklist view. I think about that it is a pretty primary situation for MVVM, however I could not discover any examples illustrating the essential conventions on how to do that.