2

I am trying to pass the selected data i'm fetching from my rest api back to the previous screen. I followed the docs, but it's not working. Not sure what I am doing wrong.

I am updating the state w/ the selected data, and know it's working bc i am printing it out in console successfully.

This is the button that calls the function to navigate back, passing the state w/ selected data in Screen B:

<Pressable onPress={() => postSelected(selectedData)} >
    <Text style={{fontSize: 13, color: 'white', fontWeight: '700', paddingRight: 5}}>{'Select'}</Text>
</Pressable>

This is the function (Screen B):

const postSelected = (selectedData) => {
    navigation.navigate({
      name: 'CreatePost',
      params: { postData: selectedData },
      merge: true
    });
}

In Screen A, I have a useEffect that listens for the selected data from Screen B:

useEffect(() => {
    if (route.params?.postData) {
      console.log('Sent');
    }
  }, [route.params?.postData]);

But it's not receiving the data.

I was following these docs: https://reactnavigation.org/docs/params/

Appreciate any help!

jdez
  • 189
  • 1
  • 10

2 Answers2

0

You can use props.navigation.getParam("postData") Method to get params from navigation

Surbhi Davara
  • 211
  • 1
  • 16
  • 1
    Thank you for replying. My error came from not wrapping params in curly braces at beginning of Screen A component. My mistake smh – jdez Jun 03 '22 at 20:39
0

The solution that worked for me and follows the best practices set by react-navigation is as follows

const MainScreen = ({ navigation }) => {

    // Here is where the returned data is detected
    React.useEffect(() => {
        if (route.params?.post) {
            // Do something with the data
        }

    }, [route.params?.post])

    const openChildScreen = () => {
        navigation.navigate('NewPostScreen')
    }
}

// ---------------------

const NewPostScreen = ({ navigation }) => {

    const goBackToMain = () => {
        // This is the data to be returned to the main screen
        const post = {
            // ...
        }
        navigation.navigate('MainScreen', { post });

    }
}