Replacing root view in TCA

How would I go about replacing the root view using TCA? The simplest scenario I can think of is to display a Login screen/flow for fresh install and display home after logging in. As well as displaying login flow after logging out. Is simple condition with bools/values from AppState enough?

struct AppView: View {
  var body: some View {
    if viewStore.loggedIn {
      HomeView()
    } else {
      LoginView()
  }
}

I do not see any issue with the solution you're suggesting, and that's how I usually do it as well.

There’s nothing wrong with this approach, but I’d suggest an enum might be a better way to model distinct states, even two, because it allows you to use those enum states to own the root state for each “mode”, for example:

enum AppState {
  case loggedOut(LoggedOutState)
  case loggedIn(LoggedInState)
}

Now, TCA doesn’t yet have great support for scoping on enum state because it is based around key paths but you can work around this by adding computed optional properties to your enum for each nested state for now.

With this in place your app scene just needs to be a WithViewStore containing two IfLetStore views, each one scoped to the logged in and logged out state respectively. Your logged out and logged in views get their own scoped stores which lets you treat the two states as distinct modules.

You could model this with two optional properties on a struct (your view would be the same as described above), with or without a Boolean property, but the enum approach means you have a compile time guarantee that you can only be in one of those states, not both or neither.

2 Likes
Terms of Service

Privacy Policy

Cookie Policy