remix-run / history

Manage session history with JavaScript
MIT License
8.29k stars 960 forks source link

Question: Is there a way to know that i have reached end of stack using history.goBack() and can't go further back. I am using historyV4 #873

Closed shreya0712 closed 2 years ago

shreya0712 commented 3 years ago

I have a use case to handle the back button differently if i have reached the end of location stack and now can not go further back. Is there a way to know if history.goBack() can take you further back or not ?

mjackson commented 2 years ago

Nope. The browser doesn't expose that information, unfortunately.

coskuncakir commented 2 years ago

Hi @shreya0712, I know that it's been quite a long time but I wanted to write my workaround for this anyway. :)

basically, I created a function that listens to changes in the navigation using the listener provided in the package and called it when the component mounts and stops listening when unmounts. it will push and pop the changes to the navigationHistory array so if the navigationHistory array's length equals 1 then you can know that no further back

check out the below snippet;

  navigationHistory = [];
  unlistenNavigationHistory = null;

  listenNavigationHistory() {
    this.unlistenNavigationHistory = history.listen(
      (location, action) => {
        if (action === 'PUSH') {
          this.navigationHistory.push(location.pathname);
        } else if (action === 'POP') {
          this.navigationHistory.pop();
        }
      },
    );
  }

  mount() {
    this.listenNavigationHistory();
  }

  dispose() {
    this.unlistenNavigationHistory();
  }
joanvf commented 2 years ago

@coskuncakir thanks for sharing. Did you manage to find any way to differentiate backward button POP events from forward button events? Otherwise, when user clicks on forward, your array will get messed up, right?

coskuncakir commented 2 years ago

hey @joanvf, sorry in my case there was only a backward button so I haven't thought about the forward scenario