Noivy
Noivy

Reputation: 129

Reload or re-render activity with react-navigation

I save data in my NewCar activity as bellow :

saveData() {
    this.retrieveData;
    this.state.DBCarName.push(this.state.CarName)
    AsyncStorage.setItem('CAR',JSON.stringify(this.state.DBCarName));            
    this.props.navigation.navigate('Home');
} 

And I retrieve it in order to display the DBCarName state in a text on my Home activity :

componentWillMount(){
    this.retrieveData();  
}

retrieveData = async () => {
    try {
        const car= await AsyncStorage.getItem('CAR')
        this.setState({ DBCarName: JSON.parse(car) })
    } catch (err) {
        console.log(err)
    }
} 

But when I press on my button that executes saveData, I go back to the Home activity in its last rendering, which means I need to reload the app to get the get the last data rendered.

Upvotes: 0

Views: 209

Answers (3)

Orhan
Orhan

Reputation: 179

You can use 'willFocus'

this.props.navigation.addListener('willFocus', (payload) => {
    this.retrieveData();
});

I used inside page's constructor.

This listener works when navigate NewCar screen even navigate with go back or android hardware back button

Upvotes: 1

Auticcat
Auticcat

Reputation: 4489

You need to either pass the params during the navigate:

    this.props.navigation.navigate("routeName", {params})

then check the params inside the componentDidUpdate of the "routeName" check the this.props.navigation.state.params

or you need to use redux.

Upvotes: 0

Kishan Bharda
Kishan Bharda

Reputation: 5700

Call this.retrieveData(); method in componentDidMount() method :

componentDidMount() {
    this.retrieveData();
}

Upvotes: 0

Related Questions