Hi everyone, happy Friday!
I just finished Day 60 and implemented all functions I had planned. I ended up having 1 bug that I cannot fix and 1 functionality that I wish to improve but don't know how to.
1. Bug
I added a feature in my UserDetail view where you can click on a user from the friends list to go to that user's UserDetail view. Here's a snippet of that.
https://github.com/lululucaschae/iFriend/issues/1#issue-1242694993
The feature works as intended. However, as you can see from the video, sometimes the back button says "Back", whereas sometimes it (correctly) displays the NavigationTitle of the previous view ("June Pollard"). I have absolutely no idea why this is happening!
Here's my UserDetailView
. (inlineForm
is a custom view extension I made. loadDataFromUrl
is a custom array extension that basically updates the User array with data from a URL.)
struct UserDetailView: View {
let source = "https://www.hackingwithswift.com/samples/friendface.json"
let user: User
@State private var usersFromUrl = [User]()
var body: some View {
Form {
Section {
inlineForm(title: "Name", value: user.name)
inlineForm(title: "Address", value: user.address)
inlineForm(title: "Company", value: user.company)
inlineForm(title: "Age", value: String(user.age))
} header: {
Text("User Info")
.font(.title3)
.padding(.bottom, 4)
}
Section {
ForEach(user.friends, id: \.id) {friend in
// Search this friend from user array and store it in thisUser
let thisUser = usersFromUrl.first{$0.id == friend.id}
NavigationLink {
UserDetailView(user: thisUser ?? user)
}
label: {Text("\(friend.name)")}
}
} header: {
Text("Friends List")
.font(.title3)
.padding(.bottom, 4)
}
}
.task {
await usersFromUrl.loadDataFromUrl(url: source)
}
.navigationTitle("\(user.name)")
.navigationBarTitleDisplayMode(.inline)
}
}
2. Improvement idea
As you can also see from the video, download happens every time you enter a new UserView
(as it's a new instance of UserView
and the user array usersFromUrl
is a private state variable inside UserView
). This will be avoided if the user array (usersFromUr
l) is a global variable that can be accessed across all views. But I don't know what the best/right way is to achieve this. (Where and how to declare this global variable).
Thank you in advance!