Chandan Singh
Chandan Singh

Reputation: 41

Reset the state of component in react native?

I want to reset the state of the component once the user revisits the page, Once the user visits page 1 and goes to page 2 and again back to page 1 <TextInput> value remains there. I want to clear once the user changes the screen, ComponentDidMount, and ComponentWillUnMount don't run on the screen change.

import React from 'react';
import { Image, TextInput, FlatList, StyleSheet, Text, View,TouchableOpacity, ActivityIndicator, Platform } from 'react-native';

export default class RatesScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currency_search: null,

    }
  }
  componentWillUnMount(){
    this.setState({currency_search:null})
  }

  render(){
    return(
      <View>
        <TextInput placeholder="Search" placeholderTextColor="#919191" ref={searchInput => { this.searchInput = searchInput }} onChangeText={currency_search => this.setState({ currency_search: currency_search.toLowerCase() }, this.searchRates)} style={{ padding: 10, borderWidth: 1, borderColor: "#171717", borderRadius: 2, backgroundColor: '#171717', color: "#919191" }} clearButtonMode="always"></TextInput>
      </View>
    )
  }

Upvotes: 2

Views: 4955

Answers (2)

Noman Hassan
Noman Hassan

Reputation: 391

You can use componentWillUnmount lifecycle hook in page1 to clear its state..

componentWillUnmount(){this.setState({})}.

Upvotes: 2

Suraj Malviya
Suraj Malviya

Reputation: 3783

If you are using react-navigation you can use navigation lifecycle callbacks,

you can use willBlur of the screen to empty your state.

The code should look like:

//This code should go in componentDidMount.
const didBlurSubscription = this.props.navigation.addListener(
 'willBlur',
  payload => {
    this.setState({}); //whatever the default state you want to set.
  }
);

// Also, Remove the listener when you are done in willUnmount
didBlurSubscription.remove();

You can study more about the navigation lifecycle callback and events here.

Upvotes: 0

Related Questions