How do I force the view class to reload in Vaadin Flow when navigating to the same view

1.2k Views Asked by At

Assuming my view is:

@Route(value="test")
public class TestView extends VerticalLayout implements BeforeEnterObserver {
    public TestView() {
        super();
        // do some stuff.
        new Button("Test", click -> getUI().ifPresent(ui -> ui.navigate("test")));
    }
    
    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        // do some other stuff.
    }
}

If I click on the Test button above then the constructor is not instantiated however the beforeEnter() method is called. In my case I would much prefer to instantiate the whole view class because the beforeEnter() method includes some logic and setup code that the view needs that if called twice can mess up the components. Specially the beforeEnter() does some checks and depending on the details may call different component rendering paths.

2

There are 2 best solutions below

0
On

Please try the code below. It removes the view (navigation target) instance from UI and then calls page reload on the client side. Then, after page reload, the next request to server will force creating a new instance of the view.

@Route(value="test")
public class TestView extends VerticalLayout implements BeforeEnterObserver {

    private final String uuid;

    public TestView() {
        super();
        // do some stuff.
        System.out.println("CTOR called");
        uuid = UUID.randomUUID().toString();

        final Element view = getElement();
        Button button = new Button("Test", click -> {
                    getUI().ifPresent(ui -> ui.getPage().setLocation("test"));
                    view.removeFromParent();
                });
        add(button);
    }

    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        // do some other stuff.
        System.out.println("Before enter");
        System.out.println("UUID = " + uuid);
    }
}

Output:

CTOR called
Before enter
UUID = 74306acc-3771-4998-aa46-19834ca9e033
CTOR called
Before enter
UUID = dbc1be2a-1bee-4da7-b676-187208621569

Hope this is something you wanted to reach.

0
On

If you are using Spring with Vaadin, you can annotate the class with

@Component
@Scope("prototype")