DEV Community

Cover image for How to Send Data while Navigating Back in React Native
Suyash Vashishtha
Suyash Vashishtha

Posted on

How to Send Data while Navigating Back in React Native

It is one of the most common issues in Mobile apps in React Native. We can send data from ScreenA to ScreenB in params but can't send data from ScreenB to ScreenA while navigating back!

But I have got a Hack!

In this blog, I am gonna tell you how to send data from ScreenB to ScreenA while navigating back.

Let's start by making Screen A

In ScreeA, I created a button to navigate to ScreenB with no data.

ScreenA

Setting up Screen B

Now in ScreenB let's make a similar button for going back, but instead of using navigation.goBack() we will use navigation.navigate() here.

Reason - In navigation.navigate() function, If the given path is present in the navigation tree, it will navigate to that path instead of creating a new one, else It will create a new path.



And as we know, ScreenA was already there in our navigation tree so navigation.navigate() will move to ScreenA which is technically our previous screen.

ScreenB

Now you might notice here, that the arguments are different from regular ones. Let me explain-

  • name - Screen/Route Name
  • data - data to be passed in routes
  • merge - true if you want to merge the data with the given screen.

With this, we can send data to ScreenA.

How to handle the new data in Screen A?

When we initialised the screen we didn’t mention any routes params data because there weren't any!
So how are we going to handle this new data in Screen A?

Code to handle data from ScreenB to ScreenA

In ScreenA we will place a useEffect for new route data with a " ? " to check if the data key exists. Initially, the data key wouldn’t exist hence it will do nothing, but after navigating back from ScreenB it will get engaged and log the new data.

Basically we are forcing new route data into our ScreenA.

And POOF, we have our data from ScreenB!

Thanks for Reading !

Top comments (0)