I made one screen that contain flatlist about accounts detail, when I input new data in other page and go back to that screen using navigation.navigate(), it still showing the last screen, not the updated one. Any advice on this?
const [childData, setchildData] = useState([]);
function readFunction(){
db
.ref('childData/' userID)
.once('value', snapshot => {
var childNameVal=[];
snapshot.forEach((child) => {
childNameVal.push({
nameVal: child.val()['childName'],
idChild: child.val()['idChild'],
})
})
setchildData(childNameVal)
});
}
<FlatList
data={childData}
renderItem={renderItem}
keyExtractor={(item) => item.idChild}
vertical
showsVerticalScrollIndicator={false}
/>
const renderItem = ({ item }) => (
<View style={{marginBottom: 20}}>
<Pressable
style={styles.baby_box}
title={item.nameVal}
>
<Text>{item.nameVal}</Text>
</Pressable>
<Pressable
style={styles.btnDelete}
value={item.idChild}
onPress={() => {
navigation.navigate('MainNavigator',{
idChild: item.idChild
});
}}
>
<Text style={styles.btnText}>Pilih</Text>
</Pressable>
</View>
);
CodePudding user response:
import { useIsFocused } from '@react-navigation/native';
Inside your component:
const isFocused = useIsFocused()
useEffect(()=>{
if(isFocused){
readFunction()
}
},[isFocused])
This will call the readFunction everytime your screen gets focused, that is every time you navigate to the screen.
CodePudding user response:
Cause: The screens maintain their last state until you update them intentionally.
You have to update the data yourself by having some updating logic. Following are the solutions.
- Reloading the screen when you want to. (Recommended)
a. Navigation.navigate.
It pushes new screen if it doesnt exist in navigation stack. If it exists it will act as pop and pass the paramaters to it. Which you can use to update the array.
b. Redux If you have already integrated redux and using it. Them you can have some "reloadScreen: boolean" paramter in reducer which you can toggle whenever you call reload action
- Reloading the screen when you come back on it.
Reload screen on focus
When you come back to previous screen it will reload data. Drawback of this it will always reload data even if you haven't change any thing on next screens.
import * as React from 'react';
import { View } from 'react-native';
function ProfileScreen({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// The screen is focused
// reload your Data
reloadData()
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
}, [navigation]);
return <View />;
}