I use react-native
with graphQL
.
I have Screen2: EditPhoto.
here, I change caption through mutation
of graphQL.
And then if I press button, it will go back to Screen1 which is Photo through navigate.goBack()
.
(Screen2 -> Screen1)
const EditValid = () => {
editPhotoMutation();
navigation.goBack();
};
<SmallButton
styleB={{ backgroundColor: `${colors.normal}` }}
styleBT={{ color: `${colors.lightgray}`, fontSize: 20 }}
text={"확인"}
onPress={handleSubmit(EditValid)}
/>
When I go back to Screen1, I want this changed caption to be applied.
But it's not, and I know that screen is only rendered once
, it's not possible.
So I searched the way to refresh Screen1.
Refresh previous screen on goBack()
According to this suggestion, I tried to use useEffect
and navigation.addListener
.
const { data, loading, refetch, fetchMore } = useQuery(FEED_QUERY, {
variables: {
offset: 0,
},
});
const [feedData, setFeedData] = useState(data?.seeFeed);
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
refetch();
setFeedData(data?.seeFeed);
});
return unsubscribe;
}, [navigation]);
what I want is simple.
I want to refetch()
Feed query again and want to put feedData
with refetched data.
But it doens't work. when I go back to Screen1, data remains same.
Please help me~~ :(
when I console.log
data, it seems when I go back to Screen1, UI is rendered again.
But refetching way
is strange..?
Because when I console.log the data, if I go back from Screen1, data is console.log-ed once again. but just data is the same.
CodePudding user response:
You can use useIsFocused() hook for this.
const isFocused = useIsFocused();
useEffect(() => {
yourFunction();
},[isFocused]);
EDIT ==> The other way and solution which worked for this particular situation:-
const [active, setActive] = useState(true);
useFocusEffect(
React.useCallback(() => {
if(active){
refresh();
setActive(false)
}
},[data?.seeFeed?.length])
);
Also had to pass data?.seeFeed directly to data prop in flatList
CodePudding user response:
This can be achived by useFocusEffect
from '@react-navigation/native'
useFocusEffect will effect every time when screen is focus
Ref: https://reactnavigation.org/docs/use-focus-effect/
import { useFocusEffect } from '@react-navigation/native';
function Profile({ userId }) {
const [user, setUser] = React.useState(null);
useFocusEffect(
React.useCallback(() => {
const unsubscribe = API.subscribe(userId, user => setUser(user));
return () => unsubscribe();
}, [userId])
);
return <ProfileContent user={user} />;
}