I am showing an alert message in my app (when a button clicked) that I want to no longer show it when “Anladım, Tekrar Gösterme(I Understand, Don’t Show Anymore)” pressed. I’ve write my code and it works. But after reopening the app, the state changes to the first value and when my button clicked it shows the alert again.
import React, {Component} from 'react';
import {StyleSheet, Text, View, ScrollView, Switch, Platform, Alert } from 'react-native';
import Hesapla from './components/hesapla';
export default class Bmh extends Component {
constructor(){
super();
this.state = {alertdit: false}
this.hesapla = this.hesapla.bind(this)
}
hesapla(){
if (this.state.alertdit === false){
Alert.alert(
'Uyarı!',
'The Alert Message The Alert Message The Alert Message',
[
{text: 'Anladım, Tekrar Gösterme', onPress: () => this.setState({alertdit: true})},
],
{ cancelable: true }
);
}
render(){
return(){
<Hesapla onPress={this.hesapla}/>}
}
The state of a component is only valid through the lifecycle of the component. Once the component is unmounted, it loses its state. For what you’re looking to do, you’d want to store it somewhere where it’ll persist. You could use something like AsyncStorage to help you store what you’re looking for. Here is some documentation on it. https://docs.expo.io/versions/v32.0.0/react-native/asyncstorage/
So the issue in your code is the fact that every time this component mounts, you’re setting in the async storage to “notseen”. So this is reseting every time you run the app. It might be better to switch it to “seen” and do nothing in the constructor. Then on the “onPress” function, set the “seen” value in async storage. That way after the first click, you set “seen” and on any next check, it will be there. Does that make sense?