navigation.getparam latest value is not accessible inside didFocus listener - react-native

I am having 2 screens in a react native app, both the screens are functional components.
A button on screen 1 leads to screen 2, I select a few checkboxes on screen 2 and click on a button to navigate to screen 1 with adding navigation params.
coming back on screen 1 runs didFocus listener, but param values are undefined, when I hit ctrl+s on in code editor, useEffect runs and values become accessible.
After this, going back to screen 1 from screen 2 runs didfocus listener (as expected) but the param values do not update.
below is useEffect code in screen 1.
useEffect(() => {
navigation.getParam('from') == 'TagFiltersScreen' ? getAllQuestions('mostInsightful', navigation.getParam('tagsFilter')) : getAllQuestions();
const listener = navigation.addListener('didFocus', () => {
navigation.getParam('from') == 'TagFiltersScreen' ? getAllQuestions('mostInsightful', navigation.getParam('tagsFilter')) : getAllQuestions();
});
return () => {
listener.remove();
}
}, []);

I faced the same issue, and here is how I am doing it.
useEffect(() => {
const isFocused = props.navigation.isFocused();
if (isFocused) {
const { params } = props.navigation.state;
navigationFocus(params);
}
const navigationFocusListener = props.navigation.addListener('willFocus', (payload) => {
const params = payload.state.params;
navigationFocus(params);
});
return () => {
navigationFocusListener.remove();
};
}, []);
const navigationFocus = (params) => {
if (params) {
}
}
I'll be curios to know if there is a better way of doing this.

Related

How to update the previous Screen's useState value and refresh the screen on click of goBack()

I want to update the previous screen's useState value and refresh the screen on click of goBack(), I know there is a useIsFocused() to do that but using this screen it is refreshing every time i goBack to the screen, suppose there is a ScreenA and ScreenB, So when user is performing any action in ScreeB then I am dispatching a value using redux and on goBack I am updating the useState value and refreshing the screenA, But it not working, I don't know what's the problem, Please help.
ScreenB
const leaveGroup = () => {
hideMenu();
callLikeMindsApi(`URL`, httpMethods.HTTP_PUT)
.then(response => {
if (response && response.data && response.data.success) {
hideMenu();
dispatch(updateHomeScreen(true));
props.navigation.goBack();
}
})
.catch(error => {
Alert.alert('FAILED', error.response.data.error_message);
});
};
And In ScreenA
const {updateValue} = useSelector(state => state.homeReducer);
useEffect(() => {
console.log('updateValue-1234', updateValue);
}); // it is printing true in console if (updateValue) { setOffset(1); setTotalPages(1); setMyChatRooms([]); getUserData(); } }, [isFocused]);
But
setOffset(1);
setTotalPages(1);
setMyChatRooms([]);
values are not updating, if I remove the if(updateValue){} and writing like this
useEffect(() => {
setOffset(1);
setTotalPages(1);
setMyChatRooms([]);
getUserData();
}, [isFocused]);
then code is working as expected, But it is refreshing every time I come back to the screenA and I want to refresh conditionally.
instead of props.navigation.goBack(); do
props.navigation.navigate('ScreenA',{details});
with the prop that you want pass
in screen A get that value in state from route params
ScreenA = (props) => {
const [navigateState] = useState(props.route.params.details|}{});
---while navigating to Screen B---
props.navigation.navigate('ScreenB',{details: navigateState});
...
I can't get full your code and understand the full logic but if you have already implemented redux you should use it like this:
const {updateValue} = useSelector(state => state.homeReducer);
useEffect(()=>{
if (updateValue) {
// update your screen juse by setting some states on the current component.
} else {
// don't update
}
}, [updateValue])
if you dispatch true value for updateValue whereever in your app then screen-A would be updated regardless it's getting focus or not. if you want to update screen-A only when it's on focus you should add focus condition in useEffect.

params is cached and shows older values on return to the same screen

I use react-navigation 5 and having issues because the params shows older values.
ScreenList.js
const handleFirstUser = () => {
const userDetail = {'name': 'First User'};
navigation.navigate('Details', { detail: userDetail});
}
const handleSecondUser = () => {
const userDetail = {'name': 'Second User'};
navigation.navigate('Details', { detail: userDetail});
}
The methods are called from a button and do go to Details Screen but the value is whichever was loaded initially:
ScreenDetails.js
const DetailsScreen = (props) =>{
const { navigation, route } = props;
const { params } = route;
const userDetail = params.name;
}
First time the app the loads, first user is loaded and correctly shows name. Then go back to the list screen, click user two. Still the first user is shown. I tried to clean up with useEffect but it doesnt have any effect:
useEffect(()=>{
return(()=>{
navigation.setParams({name: undefined});
});
}, [])
how can I reset setParams each it laods and use the values passed to it currently?

React Native hooks - correct use of useEffect()?

I'm new to hooks and ran across this setup on SO and wanted to confirm that this is the correct pattern. I was getting the RN "unmounted component" leak warning message before and this seemed to solve it. I'm trying to mimic in some way compnentDidMount. This is part of a phone number verify sign up flow and onMount I want to just check for navigation and then fire off a side effect, set mounted true and then unmount correctly.
const SMSVerifyEnterPinScreen = ({ route, navigation }) => {
const [didMount, setDidMount] = useState(false)
const { phoneNumber } = route.params
useEffect(() => {
if(navigation) {
signInWithPhoneNumber(phoneNumber)
setDidMount(true)
}
return () => setDidMount(false)
}, [])
if (!didMount) { return null }
async function signInWithPhoneNumber(phoneNumber) {
const confirmation = await auth().signInWithPhoneNumber('+1'+phoneNumber)
...
}
return (
...
)
}
RN 0.62.2 with react-nav 5 - thanks!
Since signInWithPhoneNumber is a async function and will setState you will see warning it the component is unmounted before the response is available
In order to handle such scenarios you can keep a variable to keep track whether its mounted or not and then only set state is the mounted variable is true
However you do not need to return null if component has unmounted since that doesn't accomplish anything. The component is removed from view and will anyways not render anything.
Also you do not need to maintain this value in state, instead use a ref
const SMSVerifyEnterPinScreen = ({ route, navigation }) => {
const isMounted = useRef(true)
const { phoneNumber } = route.params
useEffect(() => {
if(navigation) {
signInWithPhoneNumber(phoneNumber)
}
return () => {isMounted.current = false;}
}, [])
async function signInWithPhoneNumber(phoneNumber) {
const confirmation = await auth().signInWithPhoneNumber('+1'+phoneNumber)
...
}
return (
...
)
}

How to pass the parameter with pop in wix react-native-navigation?

how to pass parameters in pop method.
Requirement: There are two screens, screen 1 has two tabs like this: Address and Billing. There are two button on each tab layout. On click button go to screen 2 after functionality back to screen 1 but now which tab is active. If go to address tab so back to address tab same as billing tab.
Tell me how to do it?
You can pass callback while pushing screen like
Navigation.push(this.props.componentId, {
component: {
name: "Your.ScreenName",
options: {
callback:this.yourCallBackFun
}
}
});
Now while pop you can call that function like
this.props.callback();
Navigation.pop(this.props.componentId);
I think it will help you.
Screen A:
this.props.navigation.navigate('ScreenB', {func: this.func});
...
func = value => {
console.log(value);
}
Screen B:
this.props.navigation.getParam('func')();
You can call ScreenA function like this.
Screen1:
Write your navigation function and callback function in your first screen.
Pass callback function as a navigation parameter white pushing the screen.
const cbFunction = () => new Promise((resolve) => {
resolve();
});
const navigation = () => {
const { componentId } = this.props;
Navigation.push(componentId, {
component: {
name: `SCREEN_NAME`,
options: {
cbFunction: this.cbFunction
}
}
});
}
Screen2:
Write a function to go back to first screen. And call callback function from navigation parameter.
const goBack = async () => {
const { cbFunction, componentId } = this.props;
await cbFunction();
Navigation.pop(componentId);
}

React Native Navigation Passing back parameters two screen pop

I have a Screen for Main then it's push to Next for selection and passes parameters to next pushed screen and when you select something in that screen I need to pop(2) and send selected details to the main screen.
But pop didn't accept parameters. How to accomplish this.
I don't use Redux or MobX.
You need to do this
Screen A:
this.props.navigation.navigate('ScreenB', {
onPressScreenAFun: (params) => {
this.screenAFun(params)
},
})
screenAFun = (params) => {
console.log(params)
}
Screen B:
this.props.navigation.navigate('ScreenC', {
onPressScreenBFun: (params) => {
this.screenBFun(params)
},
})
screenBFun = (params) => {
const { onPressScreenAFun } = this.props.navigation.navigate.state.params
onPressScreenAFun(params)
this.props.navigation.goBack()
}
Screen C:
moveBack = (params) => {
const { onPressScreenBFun } = this.props.navigation.navigate.state.params
onPressScreenBFun(params)
this.props.navigation.goBack()
}
this is how you can pass params from Screen C to Screen A with two pop()