How to unmount a previously mounted component in stack navigator (react-navigation 2.X)?

Purnima Naik picture Purnima Naik · Feb 6, 2019 · Viewed 16.6k times · Source

This is a simplified flow of my app:-

  1. login
  2. homepage (has options to color diagram or create diagram)
  3. colorInDiagram (user colors parts of a diagram)
  4. makePayment
  5. homepage(back to homepage)

Now, after this if user decides to color a diagram again, he/she will choose that particular option from the homepage and the flow will continue as usual. This happens because after payment, the user will go back to the homepage(which is already loaded), and every other screen will reset. As the app is coming in full circle. ComponentWillUnmount is called in colorInDiagram.

What I am trying to handle:-

If the user closes the app while on step 3 (coloring the diagram), on reopening the app, I have coded it to recover from where the app was left off. But when the user finishes coloring and payment, he/she does not return to the homepage as the app directly started from the colorInDiagram component. The homepage loads for the first time.

So now when the user ties to color a diagram again from the homepage, it loads up the colorInDiagram as it was left off before the user proceeded to make payment. (It just pushes the component as it exists in the stack currently). ComponentWillUnmount is NOT called in colorInDiagram.

Expected behavior:- It should be a blank diagram with no colors filled in. As if it was a fresh mount and not just re-rendering of the component as it was left off when last used.

*Possible solution:-*I feel like I will have to manually unmount the colorInDiagram component.

The question:- How do I do manually unmount a react native component.

Also, if you guys have any other insights or problem estimates or solutions, please do share!

Answer

MaieonBrix picture MaieonBrix · Feb 7, 2019

Just so that it can be accepted as an answer here is the solution I suggested in the comment section :

You can use the StackAction.reset method : https://reactnavigation.org/docs/en/stack-actions.html#reset to reset your navigation stack where your screen rendering colorInDiagram is not in the stack anymore thus unmounting the component

From the docs :

The reset action wipes the whole navigation state and replaces it with the result of several actions.

import { StackActions, NavigationActions } from 'react-navigation';

const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({ routeName: 'Profile' })],
});
this.props.navigation.dispatch(resetAction);