I’m playing around with login functionality in my app and I’ve noticed that when a user logs out and then in again the views display data from the previous session. It doesn’t matter if the second user is a different user, it still happens.
How can I deallocate or otherwise reset my views when a user logs out?
A simplified example of my app.
@main
struct MyApp: App {
@StateObject private var authModel = AuthModel()
var body: some Scene {
WindowGroup {
if authModel.isAuthenticated && authModel.hasFreshData {
ContentView().environmentObject(authModel)
} else {
LoginView().environmentObject(authModel)
}
}
}
}
struct ContentView: View {
var body: some View {
TabView {
HomeView().tabItem { Label("Home", systemImage: "house") }
SearchView().tabItem { Label("Search", systemImage: "magnifyingglass") }
WebView().tabItem { Label("Old", systemImage: "globe" }
}
}
}
struct SearchView: View {
@State private var searchText = ""
@State private var data = [data]()
var body: some View {
NavigationStack {
List {
ForEach(data) { dat in
Text("(dat.value)")
}
}
.searchable(text: $searchText)
.onSubmit(of: .search, runSearch)
}
}
func runSearch() {
Task {
data = await HTTPClient.runSearch(searchText)
}
}
}
struct WebView: UIViewRepresentable {
var url: URL
var webView: WKWebView
func makeUIView(context: Context) -> WKWebView {
webView = WKWebView()
return webView
}
func updateUIView(_ webView: WKWebView, context: Context) {
let request = URLRequest(url: url)
webView.load(request)
}
}
class AuthModel: ObservableObject {
@Published var isAuthenticated = false
@Published var hasFreshData = false
init() {
Task {
await self.loadAuthState()
}
}
func login() async {
// Perform login request. It requires loading config and returns a complex object that contains the refresh and access token, but I don't think it's relevant for the question
isAuthenticated = true
// Save auth state
}
func fetchFreshData() asyn {
// Need to fetch some data and make sure there is a session on the server. The implementation shouldn't be relevant for this question
hasFreshData = true
}
func loadAuthState() async {
// Load the auth state
isAuthenticated = true
await fetchFreshData()
hasFreshData = true
}
}
The SearchView
uses the searchable(text:placement:prompt:)
modifier. If there is text typed into the search box it is visible when a user logs out and (a different user) logs in.
4