frzi / swiftui-router

Path-based routing in SwiftUI
MIT License
900 stars 43 forks source link

Ability to reload view when parameter changes #12

Closed joeldhenry closed 4 years ago

joeldhenry commented 4 years ago

Love the library! Im struggling to get my view to update when the parameter changes

Route(path: "/page/:id", exact: true) { route in
    return PageView(id: Int(route.parameters.id!)!)
}

first time i route to "/page/5" i can get the id and perform my api calls, however if then open "/page/6" the view isn't refreshed and i still am still looking at "/page/5". How did you resolve this issue?

struct PageView: View {

    @State var id: Int = 0

    var body: some View {
        VStack{
            Text("\(id)")
        }
    }
frzi commented 4 years ago

This happens because you're using @State. If you remove the @State, you'll see that it does get updated. 😄 Every time the path changes you render PageView. SwiftUI sees this and thinks it can just reuse the @State value.

If you insist on using @State, you can add an .id() modifier to PageView() in the Route. Like so:

Route(path: "/page/:id", exact: true) { route in
    PageView(id: Int(route.parameters.id!)!)
        .id(route.parameters.id!)
}

This tells SwiftUI that every PageView that gets rendered is different.

Thanks for checking out the project!