I’m making an app with react native.But i have a problem.
It is a problem that it returns to the initial state even if a character is entered in the text input.
This is my code.
import React, {useState, Compomen, useEffect} from 'react';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import {View, TextInput, StyleSheet, Text, TouchableOpacity, Image} from 'react-native';
import AsyncStorage from "@react-native-async-storage/async-storage";
function DetailScreen({ navigation, route }) {
const { day } = route.params;
const [title,setTitle] = useState("");
const handleChangeTitle = (text) => {
setTitle(text)
_savediary();
}
const _readdiary = async () => {
try {
const hello = await AsyncStorage.getItem(dateString + "diary");
if (hello == null) {
setTitle("Write your day here.")
}else{
setTitle(hello);
}
} catch(error) {
console.error(error);
}
}
const _savediary = async () => {
try {
await AsyncStorage.setItem(dateString + "diary", title);
} catch(error) {
console.error(error);
}
}
var dateString = "";
for (var key in day) {
console.log("key:" + key + "/" + day[key])
dateString = day[key];
}
useEffect(() => {
_readdiary();
})
return(
<SafeAreaProvider>
<View style={{flexDirection: 'column'}}>
<View style={{flexDirection: 'row'}}>
<Text style={styles.date}> {dateString}</Text>
<TouchableOpacity activeOpacity={0.5} onPress={() => navigation.push('Mood', {day})}>
<Image
source={require('./assets/select.png')}
style={styles.sticker}
/>
</TouchableOpacity>
</View>
<TextInput
style={{padding: 10}}
onChangeText={handleChangeTitle}
editable
multiline
value={title}
/>
</View>
</SafeAreaProvider>
);
}
const styles = StyleSheet.create({
input_container: {
borderWidth: 0.5,
padding: 15,
fontSize: 16,
marginTop: 20,
borderRadius: 50,
},
date: {
fontSize: 30,
width: "75%"
},
sticker: {
height: 50,
width: 50,
},
center: {
flex: 1,
alignItems: "center"
},
});
export default DetailScreen;
I think this is a code flow issue, but I don’t know how to solve it.
Is it correct that the code flow is causing this problem?
And do you know how to solve this problem?
If you know, please reply.
Thanks.
>Solution :
You were wrong with using useEffect hook.
_readdiary function will be calling every time.
There is a second parameter including [] like this:
useEffect(() => {
_readdiary();
}, [])
