Handling the android back button in a react native application

On screen A, I have a dropdown with its default state set. When a new value is selected from the dropdown, the state updates and navigates to a new screen with data based on the updated state. In the new screen, there is a back button in the header as well as the android device's back button.

Clicking either the android back button or the header back button takes me back to the previous screen, but I want to reset the dropdown's state when returning to the previous screen so that it shows the original default option.

class DropdownSales extends Component {

    constructor(props) 
    {
        super(props)

        this.state = {

            oem : 'all',
            oem_type : [],
            pickerSelection: 'OEM Wise',
            pickerDisplayed: false,

        }
    }

fetch_default = () => 
    {           
        var headers = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Headers': 'x-access-token',
            'x-access-token': this.state.id
        }

        axios.post('http://**********************', {
            oem: this.state.oem
        }, {headers: headers})
        .then((res) => 
        {

            let TotalSales = res.data.data[0].TotalSales;

            })
        .catch(err => {
            console.log(err)
        });
    }


    setPickerValue = (newValue) => 
    {

        this.props.navigation.navigate('OemLevelTwo', {value: newValue});
        this.setState({
          pickerSelection: newValue
        });

        this.togglePicker();           
    }

      togglePicker = () => {
        this.setState({
          pickerDisplayed: !this.state.pickerDisplayed
        })
      }


render() {
return (
            <View>
                <View style={{flexDirection:'row', justifyContent:'space-between'}}>

                <TouchableOpacity onPress={() => this.togglePicker()} style={{flexDirection:'row', marginTop:10, marginLeft: 10}}>

                    <Text>
                        { this.state.pickerSelection }
                    </Text>
                    <Icon name="arrow-drop-down" color='#000' size={20}/>
                </TouchableOpacity>
                    <Modal 
                        visible={this.state.pickerDisplayed} 
                        animationType={"fade"} 
                        transparent={true}
                        onRequestClose={ () => {
                        this.setState({
                            pickerDisplayed: !this.state.pickerDisplayed
                        })
                    }}>
                        <View style={{ margin: 15, padding: 20,
                            backgroundColor: '#efefef',
                            bottom: 60,
                            alignItems: 'center',
                            position: 'absolute' }}>

                            { oem_type.map((value, index) => {
                            return <TouchableOpacity key={index} onPress={() => this.setPickerValue(value)} style={{ paddingTop: 4, paddingBottom: 4 }}>
                                <Text>{ value }</Text>
                                </TouchableOpacity>
                            })}

                        </View>
                    </Modal>                       
                </View>
            )
    }
}

The initial placeholder text in the modal dropdown is currently 'OEM Wise'.

When a value is selected from the dropdown, the state pickerSelection reflects the new selection, such as 'model A'. I would like it to show 'OEM Wise' in pickerSelection when returning from the new screen.

Any assistance would be greatly appreciated.

Answer №1

To receive updates on the navigation life-cycle, simply utilize the addListener method. This will enhance your screen's functionality without altering anything else.

constructor(props) {
    super(props)

    /* Your existing code here */

    this.didFocusSubscription = this.props.navigation.addListener('didFocus', () => {
        this.setState({ /* Add your new state here */ })
    });
}

componentWillUnmount() {
    this.didFocusSubscription.remove();
}

For more detailed information, you can refer to this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason that BitmapFactory decreases the size of my image by a factor of 1.333 instead of 2?

I am currently working with a PNG image file that has dimensions of 2236x971px. My goal is to scale it down by a factor of two, essentially reducing it by half. However, when I attempted to achieve this using the following code: BitmapFactory.Options bo = ...

Phonegap apk is experiencing issues with external links not functioning as intended

Has anyone encountered issues with external links not working in a PhoneGap APK? I began developing an application using PhoneGap and tested it on the desktop app, where everything worked perfectly. However, when I generated the APK using PhoneGap Build, ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

What is the best way to retrieve data in Vue from Node.js?

app.js router.get('/', (req, res) => { var cart = req.cookies.cart; res.sendFile(path.join(__dirname,'../../src/components/cart.html'),cart); }) shoppingCart.html <body> <div id="shop" class="container mt-3"&g ...

Ways to update a nested object by utilizing the setState method

I have a situation where I need to modify the key/value pairs of an object in my state. Specifically, I need to add a key/value pair to the object with an ID of 13. Please refer to the attached photo for reference. Although I know how to use setState, I ...

Error Reference: The variable "angular" has not been properly defined in line 1 of the app.js

WelcomePage.js angular.module("travel") .controller('LoginCtrl', function($scope, AuthService, $ionicPopup, $state) { $scope.user = { name: '', password: '' }; $scope.login = function() { AuthService.login ...

Create a circle-shaped floor in THREE.JS that mimics the appearance of a shadow

I am working on creating a circle mesh with a gradient material that resembles a shadow effect. Specifically, I want the circle to have a black center and fade to almost white at the edges. Currently, I have been able to create a circle and position it co ...

NPM issue: unable to locate module 'internal/fs' in Node.js

Encountering NPM error after updating to Node version 7.x. npm is now non-functional and the cause remains unidentified. Possible reason for the issue could be - npm ERR! Cannot find module 'internal/fs'. The output generated when execu ...

How can you ensure that an event is added only once when using mouseover functionality?

One approach involves utilizing an event listener that operates as follows (in pseudo code): canvas.onmousemove = function (e) { checkCollision(e); }; var checkCollision = function(e){ var context = canvas.getContext('2d'); var coordina ...

The animation feature does not work on all elements individually

I am encountering an issue with my progress bar where the data-percent attribute is not being applied correctly. Each pro-bar has a different data-percent value, but in the browser, the first pro-bar's data-percent value is being applied to all of the ...

Is it true that eliminating white spaces can enhance a website's loading speed?

I'm curious about something. Can removing white space actually make a website load faster? For instance, take a look at the following CSS snippet - body{ overflow-wrap:break-word; word-break:break-word; word-wrap:break-word } .hidden{ display:none } . ...

Failure to validate two dates, even when they are both in date format within AngularJS

Although it may seem silly to ask, I am confused as to why this is not working. Even though all the values appear fine in debug mode. My goal is to display an error if the productionStartFrom date is before the current date. Controller scope.currentDate ...

What are the steps to successfully deploy a static website created with Next.js on Vercel?

Using the Next.js static site generator, I created a simple static site that I now want to deploy on Vercel. However, I keep encountering an error during the build process. While I have successfully deployed this site on other static hosting platforms befo ...

Having trouble retrieving object values from the request body during a POST request in [Node.js, MySQL]

I am currently developing a management system and working on creating POST requests for the API to add a new city to the database. However, I am facing an issue where instead of receiving the correct values from the request's body, I am getting "undef ...

What is the best way to define a default value for a v-text-field in Vuetify within a Nuxt.js project?

As a beginner with vuejs and nuxtjs, I have been introduced to vuetify at my workplace. I am currently trying to set the default value of 0 for v-text-field fields in the application, but unfortunately, I cannot seem to find this information in the vueti ...

Clear v-model without changing its associated values

I'm facing an issue with my <input> fields, which look like this: <input type="text" v-model=user.name" /> <input type="text" v-model="user.phone" /> <button @click="add">add user</button> Whenever the add user button i ...

Adding a child element is unable to function within two circular objects

I am having trouble when trying to append two circles in my code. The first circle is created and appended to the group perfectly fine, but the second smaller circle that should be appended inside the first one is not showing up at all. I'm not sure w ...

Error Encountered in Xamarin Forms: System.ObjectDisposedException

I am encountering an issue where I receive an ObjectDisposedException when trying to change a list item's property from another screen. Below is the code snippet of my renderer: namespace SmartwebsCrossPlatform.CustomRenderers { public class Grad ...

Oops! There seems to be an error in my code - it's expecting a semicolon. I'm currently working on developing an authentication system using credentials with next auth

#pages/api/auth I'm currently in the process of developing an authentication system using Nextauth in Next Js. I encountered an issue with authenticating using credentials while following a tutorial on YouTube.I've double-checked the syntax multi ...

Stopping Angular Route Alteration Depending on Routing Conditions

I have been searching everywhere for a solution to this issue. My goal is to be able to access the routing parameters collection and prevent the route from loading if a certain parameter is missing. I have tried using preventDefault in $routeChangeStart, b ...