Answer the question
In order to leave comments, you need to log in
Can useEfffect indirectly call itself if it changes the state it is bound to?
There is a small React Native utility made in Expo, and it has a component that lists text files in the program directory and gives you the option to delete the file or send it by mail:
function SendSurveyScreen({ route, navigation }) {
const { surveyerName, otherParam } = route.params
const [fileResponse, setFileResponse] = useState([]);
const [selectedId, setSelectedId] = useState(null);
const [sName, setSName] = useState(surveyerName)
const Item = ({ item, onPress, backgroundColor, textColor }) => (
<TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}>
<Text style={[styles.title, textColor]}>{item.title}</Text>
</TouchableOpacity>
);
const renderItem = ({ item }) => {
const backgroundColor = item.id === selectedId ? "#6e3b6e" : 'lightblue';
const color = item.id === selectedId ? 'white' : 'black';
return (
<Item
item={item}
onPress={() => setSelectedId(item.id)}
backgroundColor={{ backgroundColor }}
textColor={{ color }}
/>
);
};
const readFiles = async () => {
try {
return (await FileSystem.readDirectoryAsync(FileSystem.documentDirectory))
.map((value, index) => {
console.log(value.slice(-4))
return value.slice(-4) == '.txt' ? { id: index, title: value } : null
});
} catch (err) {
console.warn(err);
}
}
useEffect(() => {
let isMounted = true;
readFiles().then(data => { if (isMounted) setFileResponse(data) });
return () => { isMounted = false };
}, [fileResponse])
//Получаем имя файла по номеру в списке
const getFileByID = (files, id) => {
const retFile = files.find(file => file.id == id)
return retFile.title
}
...
return (
<SafeAreaView style={styles.container}>
<FlatList
data={fileResponse}
renderItem={renderItem}
keyExtractor={(item) => item.id}
extraData={selectedId}
/>
<Text></Text>
<Button
title='Отправить файл по электронной почте'
disabled={selectedId == null}
onPress={() => {
emailFile(getFileByID(fileResponse, selectedId))
}}
/>
<Button
title='Удалить файл'
disabled={selectedId == null}
onPress={() => {
Alert.alert(
"Вы уверены?",
"Вы точно хотите удалить данные? Эту операцию нельзя отменить.",
[
{ text: "Нет, оставим", style: 'cancel', onPress: () => { } },
{
text: "Да, удалить",
style: 'destructive',
onPress: () => {
FileSystem.deleteAsync(FileSystem.documentDirectory + getFileByID(fileResponse, selectedId))
.then(value => console.log(value))
.catch(e => console.log(e))
setFileResponse([])
setSelectedId(null)
},
},
]
);
}
}
/>
<Button
title='На главный экран'
onPress={() => navigation.navigate('Старт')}
/>
</SafeAreaView>
);
};
Answer the question
In order to leave comments, you need to log in
least
useEffect(() => {
let isMounted = true;
readFiles().then(data => { if (isMounted) setFileResponse(data) });
return () => { isMounted = false };
}, [fileResponse])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question