I want to call a class function on drawer open and drawer close event can any one help me with this as i am new at react native.
const defaultGetStateForAction =Drawer.router.getStateForAction;
Drawer.router.getStateForAction = (action, state) => {
if(state && action.type === 'Navigation/OPEN_DRAWER' ) {
Alert.alert("drawerOpen")
//here call a class function with true value
}
if(state && action.type === 'Navigation/DRAWER_CLOSED') {
Alert.alert("drawerClose")
//here call a class function with false value
}
Use the below code to solve your problem
Related
Function :
async function ridirect(APIresponse) {
const { navigate } = this.props.navigation;
if(APIresponse.success == true){
navigate('HomeBottomBar')
}
}
this function was getting error.
It's you're not passing the navigation prop to the component. You could use Navigation Context to pass navigation to the function.
E.g.:
import { NavigationContext } from '#react-navigation/native';
async function ridirect(APIresponse) {
const contextType = NavigationContext;;
if(APIresponse.success == true){
navigate('HomeBottomBar')
}
}
I'm trying to find a way to execute a function upon termination of the app, what function can I use to do this in react native?
Basically, whenever the user closes the app (completely terminate).
This might help:
AppState.addEventListener('change', state => {
if (state === 'active') {
// do this
} else if (state === 'background') {
// do that
} else if (state === 'inactive') {
// do that other thing
}
});
You can use the AppState API provided by react-native in your root component where you register/mount your app.
There you can add an onChange eventlistener to AppState which executes your custom function whenever AppState.currentState.match(/inactive|background/) returns true. Your custom function however should be isolated from your other component states.
I am using react-native where my first screen is Welcome screen and I want to set dashboard on my first screen when the user is login.
Here is my code:
componentWillMount(){
var self = this;
AsyncStorage.getItem(AppStrings.contracts.IS_LOGGED_IN).then((json) =>{
try{
var userDetail = JSON.parse(json);
if(userDetail.isLoggedIn != undefined && userDetail.isLoggedIn == true){
Actions.dashboard();
}
}catch(e){
}
})
}
I set this code on the Welcome screen and its working fine in IOS. But in android issue is it shows the Welcome screen for 5 to 10 seconds before going to dashboard screen when the user is login.
Here I am using react-native-router-flux for the navigation bar.
Because AsyncStorage.getItem() is asynchronous, your render() function is being called BEFORE it has been fulfilled.
So the flow of your application is:
Call componentWillMount()
AsyncStorage.getItem()
render() - This is where you see your Welcome Screen for 5-10 seconds
AsyncStorage has been fulfilled - .then() and then the User gets redirected to the dashboard.
I would set an isLoaded flag in your state:
constructor() {
super();
this.state = {
isLoaded: false,
}
}
Then inside of your componentWillMount() function, set the value to true once AsyncStorage has fulfilled its Promise.
try {
var userDetail = JSON.parse(json);
if(userDetail.isLoggedIn != undefined && userDetail.isLoggedIn == true){
Actions.dashboard();
}
this.setState({ isLoaded: true });
}
And finally, I would add some sort of loading indicator inside of render() to show the User that your application is still performing some logic.
render() {
if(this.state.isLoading) {
return <Text>I am loading</Text>
} else {
return ...
}
}
When press on any button on my React Native App to navigate to a different screen multiple times, then it will redirected to the next screen multiple times.
My sample code is:
// This is my button click event
myMethod()
{
this.props.navigation.navigate("ScreenName")
}
I am using react-navigation to navigate through my app.
How can I fix this behaviour?
I think there are a few ways this could be done. Perhaps recording when the navigation has occurred and preventing it from navigating multiple times.
You may also want to consider resetting hasNavigated after an amount of time etc as well.
// Somewhere outside of the myMethod scope
let hasNavigated = false
// This is my button click event
myMethod()
{
if (!hasNavigated) {
this.props.navigation.navigate("ScreenName")
hasNavigated = true
}
}
This react-navigation issue contains a discussion about this very topic, where two solutions were proposed.
The first, is to use a debouncing function such as Lodash's debounce that would prevent the navigation from happening more than once in a given time.
The second approach, which is the one I used, is to check on a navigation action, whether it is trying to navigate to the same route with the same params, and if so to drop it.
However, the second approach can only be done if you're handling the state of the navigation yourself, for example by using something like Redux.
Also see: Redux integration.
One of solution is custom custom components with adds debounce to onPress:
class DebounceTouchableOpacity extends Component {
constructor(props) {
super(props);
this.debounce = false;
}
_onPress = () => {
if (typeof this.props.onPress !== "function" || this.debounce)
return;
this.debounce = true;
this.props.onPress();
this.timeoutId = setTimeout(() => {
this.debounce = false;
}, 2000);
};
componentWillUnmount() {
this.timeoutId && clearTimeout(this.timeoutId)
}
render() {
const {children, onPress, ...rest} = this.props;
return (
<TouchableOpacity {...rest} onPress={this._onPress}>
{children}
</TouchableOpacity>
);
}
}
another: wrap onPress function into wrapper with similar behavior
const debounceOnPress = (onPress, time) => {
let skipCall = false;
return (...args) => {
if (skipCall) {
return
} else {
skipCall = true;
setTimeout(() => {
skipCall = false;
}, time)
onPress(...args)
}
}
}
I want to dispatch a action when drawer close.But I don't know I need write what function, can you help me.
You need to custom navigation actions to know when the DrawerClose event fired.Here is a simple example:
const MyAppDrawerNavigator = DrawerNavigator({
//...
});
const defaultGetStateForAction = MyAppDrawerNavigator.router.getStateForAction;
MyAppDrawerNavigator.router.getStateForAction = (action, state) => {
if (state && action.type === 'Navigation/NAVIGATE' && action.routeName === 'DrawerClose') {
console.log('DrawerClose');
//dispatch whatever action you want
}
return defaultGetStateForAction(action, state);
};
To known more about how to custom routers, see here.