Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Refresh previous Drawer Screen calling from 2nd Screen in Drawer navigation in React-native?

In my React-Native project I am using one Navigation drawer. In that drawer I declared two screens - NoteMeHome and MakeNote. Initially the NoteMeHome starts as an initial route of Drawer Navigation. From the NoteMeHome.js (first screen) class I go to the MakeNote.js (Second Screen). In this MakeNote.js class I have used one form to fill. After filling the Form when user clikcs submit it will go back to the previos Screen ( NoteMeHome.js) and as there is an API call in this NoteMeHome.js class, it will refresh and show the submitted data.

But whenever I am going from MakeNote Screen to NoteMeHome Screen, It just changes to back stack but the the NoteMeHome Screen is not refreshed as it is showing the old data.

To control the Drawer flow and structure I have created a class named -

NavigationDrawerStructure.js

class NavigationDrawerStructure extends Component {
  static navigationOptions = {
    header: null ,
  };

  toggleDrawer = () => {
    this.props.navigationProps.toggleDrawer();
  };
  render() {
    return (
      <View style={{ flexDirection: 'row' }}>
        <TouchableOpacity onPress={this.toggleDrawer.bind(this)}>
          {/*Donute Button Image */}
         <Icon name='menu'/>
        </TouchableOpacity>
      </View>
    );
  }
}
const FirstActivity_StackNavigator = createStackNavigator({
  First: {
    screen: NoteMeHome,
    navigationOptions: ({ navigation }) => ({
      title: 'Home',
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,

      headerStyle: {
        backgroundColor: '#FF9800',
      },
      headerTintColor: '#fff',
    }),
  },

});

const Screen2_StackNavigator = createStackNavigator({
  Second: {
    screen: MakeNote,
    navigationOptions: ({ navigation }) => ({
      title: 'Create Note',
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,

      headerStyle: {
        backgroundColor: '#FF9800',
      },
      headerTintColor: '#fff',
    }),
  },
});



const Drawer = createDrawerNavigator({
  Screen1: {
    screen: FirstActivity_StackNavigator,
    navigationOptions: {
      drawerLabel: 'Home',

      drawerIcon: (
        <Icon name='home' size={24}

        />
      )

    },
  },

  Screen2: {
    screen: Screen2_StackNavigator,
    navigationOptions: {
      drawerLabel: 'Create Note',
      drawerIcon: (
        <Icon name='home' size={24}

        />
      )
    },
  },

});

const DrawerNavigatorExample = createStackNavigator({
  Drawer: { screen: Drawer, navigationOptions: { header: null } },
  ScreenExternal: {
    screen: ScreenExternal,
    navigationOptions: { title: 'Screen External' },
  },
});

export default createAppContainer(DrawerNavigatorExample);

In the MakeNote.js(Second Screen) I use one function submit to a POST request. Here's the code for that-

submit() {
    this.setState({isLoading:true})
    let collection = {}
    collection.timestamp = this.state.timestamp,
    collection.status = this.state.status,
    collection.title = this.state.title,
    collection.detail = this.state.detail,
    collection.url = this.state.url,
    collection.mail = this.state.mail,
    collection.phone = this.state.phone,
    collection.category = this.state.category

    console.log('#HELLO:', collection);

    var url = 'my url';

    if(collection.title != '' ) {

            if(this.state.isNetConnected != false) {

              fetch(url, {
                method: 'POST',
                body: JSON.stringify(collection),
                headers: new Headers({
                  'Content-Type' : 'application/json',
                  'token': 'abcd',
                  'jwt': this.state.getValue

                })
              }).then(response =>
                {
                  this.setState({isLoading:false});
                  if (response.status !== 200) {
                      console.log('Status Code: ' + response.status);
                      return;
                  }

                  response.json().then(data =>{
                      console.log(data);
                      if(data.status == "saved") {
                        this.props.navigation.navigate('First'); 
                    }
                  });
              }
                )
              .catch(error=>{
                this.setState({isLoading:false})
                console.error('Error:', error)

              })

            } else{
              this.setState({isLoading:false});
              Alert.alert("Oops!! No Internet Connection Available");
            }

    } 

    else {
      this.setState({isLoading:false})
      Alert.alert('Please fill up the required field');
    }

  }

In the submit function you can see the below line initialize the previous screen back-

  if(data.status == "saved") {
                        this.props.navigation.navigate('First'); 
                    }

It shows the NoteMeHome(First Screen) back but no data has been refreshed.

So, I need a solution to refresh this NoteMeHome Screen and show the latest data by API call.

like image 279
S. M. Asif Avatar asked Nov 06 '22 18:11

S. M. Asif


1 Answers

You can pass a callback function as parameter when you call navigate .

Inplace of :

this.props.navigation.navigate('First');

Add This:

this.props.navigation.navigate('First', {
      onGoBack: () => this.refresh(),
    });

Then add callback function :

refresh() {
  this.doSomething();
}

Hope it helps !

like image 95
abhinandan sharma Avatar answered Nov 09 '22 23:11

abhinandan sharma