cooperka / react-native-snackbar

:candy: Material Design "Snackbar" component for Android and iOS.
Other
815 stars 150 forks source link

Perform action once snackbar disappears #168

Closed mikeymop closed 3 years ago

mikeymop commented 3 years ago

I like this library because the snackbar can display over react navigation so that it displays through a page change.

I am using this to manage drafts on a form I use. If the form is changed and the user goes back, the snackbar will display saying 'Saving as Draft' and offers an 'undo' button.

Because there is not something like an 'onDismiss' property on this snackbar, I use setTimeout((), Snackbar.LENGTH_SHORT) before calling the snackbar. I then save the draft (a redux dispatch) when the timeout runs out.

This however runs into issues with redux because the state of the screen I was on was destroyed this throws an error in the redux library.

this.navigation.addListener('beforeRemove', (e) => {
      // Prevent default behavior of leaving the screen
      e.preventDefault();
      const unsaved = this.state.unSavedChanges;
      console.log(`unsaved changes? ${unsaved ? "Yes" : "No"}`);
      if (unsaved) {
        // If we don't have unsaved changes, then we don't need to do anything
        console.log(`Save Draft?`);

        setTimeout(() => this.SaveDraft(), Snackbar.LENGTH_SHORT);

        // Prompt the user before leaving the screen
        Snackbar.show({
          text: 'Saved as Draft',
          duration: Snackbar.LENGTH_SHORT,
          action: {
            text: 'Undo',
            textColor: 'orange',
            onPress: () => { this.navigation.dispatch(e.data.action);},
          },
        });
        this.navigation.dispatch(e.data.action);
        return;
      } else {
        this.navigation.dispatch(e.data.action);
      }
    });

Is it at all possible to detect when the snackbar is doing to disappear besides using the duration constants?

cooperka commented 3 years ago

Unfortunately there's no way to do this currently, as it would need to be supported by the Android library itself. You'll need to refactor your code so that calling saveDraft() can be done outside of a screen context. Good luck!