The `testDeviceID` prop of AdMobBanner is deprecated. Test device IDs are now set globally. Use AdMob.setTestDeviceIDAsync instead - react-native

I've recently been producing an app on a real-native basis. I also put in an ad banner using Google's admob There is no advertisement that used to appear until a few days ago.
Setting the admob props below will result in an error.
<AdMobBanner
bannerSize="banner"
adUnitID="ca-app-pub-#######"
testDeviceID="EMULATOR"
servePersonalizedAds = {true}
onDidFailToReceiveAdWithError={this.bannerError}
/>
The errors are as follows.
The `testDeviceID` prop of AdMobBanner is deprecated. Test device IDs are now set globally. Use AdMob.setTestDeviceIDAsync instead.
I'd appreciate it if you could help me.

I had the same problem, They should update the information on the Expo site. I believe this should work for the banner as well.
Import:
import {
setTestDeviceIDAsync, //<--- I forgot this first time
AdMobInterstitial
}from 'expo-ads-admob';
init after mount:
componentDidMount(){
this.initAds().catch((error) => console.log(error));
}
initAds = async () => {
AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/1033173712') //test id
await setTestDeviceIDAsync('EMULATOR');
}
Trigger this function from a button or what ever you like:
_openInterstitial = async () => {
try {
this.setState({ disableInterstitialBtn: true })
await AdMobInterstitial.requestAdAsync()
await AdMobInterstitial.showAdAsync()
} catch (error) {
console.error(error)
} finally {
this.setState({ disableInterstitialBtn: false })
}
}

Related

How to call API inside expo SplashScreen?

I'm new in react native so I can't figure out how to add an API call inside SplashScreen in react -native app. The context - I'm building a react-native app expo, which on app load should send API GET request to the backend to get order data, and based on that data I'm either displaying screen A(delivered) or B(order on it's way). I want to add this API call inside the SplashScreen when app still loads so when app is loaded there is no delay in getting API data and displaying screen A/B.
I have a simple useEffect function to call API like this:
const [data, setData] = useState{[]}
useEffect(() => {
const getData = async () => {
try {
const response = await axios.get(url);
if (response.status.code === 200 ) {
setData (response.data) // to save data in useState
}
} else if (response.status.code != 200) {
throw new Error();
}
} catch (error) {
console.log(error);
}
};
getData();
}, []);
and then in the return:
if (data.order.delivered) {
return <ScreenA />
}
else if (!data.order.delivered) {
return <ScreenB />
else {return <ScreenC />}
The issue is that sometimes if API is slow, then after splash screen app has a white screen, or ScreenC can be seen. How can I call API in the splashscreen while app is loading and have a nicer ux?
you can make a custom hook with simple UseState and put it after you've fetched your data
const [loading, setLoading] = useState(true)
...
useEffect(() => {
const getData = async () => {
try {
const response = await axios.get(url);
if (response.status.code === 200 ) {
setData (response.data)
// When data is ready you can trigger loading to false
setLoading(false)
}
...
and After that, you can use a Simple If statement on top of your app.js file
like this
if (!loaded) {
return <LoadingScreen/>; // whetever page you want to show here ;
}
you can use expo expo-splash-screen to achieve this goal:
call this hook on mount...
import * as SplashScreen from 'expo-splash-screen';
const [appIsReady, setAppIsReady] = useState(false);
useEffect(() => {
async function prepare() {
try {
// Keep the splash screen visible while we fetch resources
await SplashScreen.preventAutoHideAsync();
// Pre-load fonts, make any API calls you need to do here
await Font.loadAsync(Entypo.font);
// Artificially delay for two seconds to simulate a slow loading
// experience. Please remove this if you copy and paste the code!
await new Promise(resolve => setTimeout(resolve, 2000));
} catch (e) {
console.warn(e);
} finally {
// Tell the application to render
setAppIsReady(true);
}
}
prepare();
}, []);
you can also check expo doc

Unable to set useState variable in async method and console log it

Im working with my friends on a app project and we find an issue many times when we tring to set a use state and the console log the variable, i've looking for a solution in the website and saw that the reason is that the usestate is an async awiat which means the variable that i set in the use state isn't immidatly set in it, so i tried many solution that i found in the websites but none of them work for me.
in the screenShot you can see that the json variable is in console log before and the set varaible doesn't show after the setActiveUser , any help?
Thanks!
If you want to do something upon setting state then your best bet is to use the useEffect hook from React and adding your state in the dependency array. This will then call the function in your useEffect every time the state changes. See below a rough example:
import { Text } from 'react-native';
const MyComponent = () => {
const [activeUser, setActiveUser] = useState(null);
useEffect(() => {
// This should log every time activeUser changes
console.log({ activeUser });
}, [activeUser]);
const fetchAuthentication = async user => {
var flag = false;
await fetch('/api/authUser/', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user),
})
.then(res => {
res.ok && (flag = true);
return res.json();
})
.then(json => {
if (flag) {
setActiveUser(json);
}
})
.catch(error => console.error(error));
return flag;
};
return <Text>Hi</Text>;
};
Full documentation: https://reactjs.org/docs/hooks-effect.html

Error: verifier._reset is not a function. when trying to Sign in with phone using firebase, react native and Expo

I am trying to implement Phone Sign In in mu react native app, but I am getting the following error:
verifier._reset is not a function. (In 'verifier._reset()', 'verifier._reset' is undefined)
at http://192.168.1.2:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&minify=false:126633:27 in <unknown>
at node_modules/tslib/tslib.js:60:8 in createExporter
at node_modules/tslib/tslib.js:18:0 in <global>
at http://192.168.1.2:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&minify=false:116838:35 in rejected
This is how I have tried to implement the signing:
const SignUp = () => {
const [phoneNumber, setPhoneNumber] = useState("")
const recaptchaVerifier = React.useRef(null);
const auth = getAuth(app)
const sendCode = async () => {
console.log(recaptchaVerifier.current)
signInWithPhoneNumber(auth, phoneNumber, recaptchaVerifier.current!)
.then(r => {
console.log("Hej!")
}).catch(err=>{
console.log(err)
})
}
return (
<SafeAreaView
style={tw.style('w-full')}>
<FirebaseRecaptchaVerifierModal
ref={recaptchaVerifier}
firebaseConfig={app.options}
attemptInvisibleVerification={true}
/>
<TextInput
style={tw.style('w-1/2', 'shadow', 'border', 'rounded', 'py-2', 'px-3', 'text-gray-700')}
onChangeText={setPhoneNumber}
keyboardType="phone-pad"
/>
<Button title={"Send Code"} onPress={sendCode}/>
</SafeAreaView>
)
}
export default SignUp
I have also tried to implement it like this:
const phoneProvider = new PhoneAuthProvider(auth) const verificationId = await phoneProvider.verifyPhoneNumber(phoneNumber, recaptchaVerifier.current!)
but I get the same result.
I am all out of ideas, so any help would be much appreciated.
Updating to the latest version of expo-firebase-recaptcha should fix it.
Open this file:
node_modules\expo-firebase-recaptcha\build\FirebaseRecaptchaVerifier.js
And add
export default class FirebaseRecaptchaVerifier {
token;
constructor(token) {
this.token = token;
}
get type() {
return 'recaptcha';
}
async verify() {
return this.token;
}
async _reset(){
}
}
add the _reset() function there and save it! the error will be fixed.
This answer is close, but even after patching the package I had the same problem. This appears to be a recent issue, and the OP is using the Modal form, not the raw verifier.
Instead, add the following to node_modules/expo-firebase-recaptcha/build/FirebaseRecaptchaVerifierModal.js around line 31:
async _reset() {
return
}
Just update your expo package, it has been resolve. (see here)

React native fetch api call is not making the request

I am using an api call to get information for my app which I display to the user. The problem is that when I open the screen for the first time the app displays the information but when I go to a different screen and then comeback I dont see the information unless I restart the app.
This function makes the apiCall for me:
async function getOrders() {
var retrieveData = async () => {
try {
var value = await AsyncStorage.getItem("user");
var data = JSON.parse(value);
return data.user.email;
} catch (error) {
alert(error);
}
};
retrieveData().then((usr) => {
setUser(usr)
fetch(URL + "/api/order/quoted", {
method: "POST",
body: "user=" + usr,
headers: { "Content-type": "application/x-www-form-urlencoded" },
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.error === null) {
setOrders(responseJson.orders);
}
});
});
}
First I use the retriveData function to get the used id, based on that information is server to the user.
You are using react-navigation version 5, so you need to wrap your logic fetch data in useFocusEffect hook react navigation docs
import { useFocusEffect } from '#react-navigation/native';
useFocusEffect(
React.useCallback(() => {
getOrders()
}, [getOrders])
);
The problem can be solved in the following steps:
If you want the data fetched from your endpoint to be used even if you move to other screen use Redux.
If you use redux or not and want to fetch the api every time you open a specific screen then you need to add an onfocus listener. An example is here https://reactnavigation.org/docs/navigation-events/
class Profile extends React.Component {
componentDidMount() {
this._unsubscribe = navigation.addListener('focus', () => {
// do something
});
}

orientation change listener in expo react native not firing?

i want to detect the current orientation of device in expo react native, this is my code that doesn't work:
import {
Dimensions,
} from 'react-native';
import * as ScreenOrientation from 'expo-screen-orientation';**
const App = () => {
...
useEffect(() => {
const isPortrait = () => {
const dimension = Dimensions.get('screen');
return dimension.height >= dimension.width;
};
Dimensions.addEventListener('change', () => {
const orientation = isPortrait() ? 'portrait' : 'landscape';
console.log('Dimensions orientation', orientation);
});
ScreenOrientation.addOrientationChangeListener((e) => {
console.log('e ', e);
});
}, []);
how ever when i rotate the device there is no logs so it's not firing?
This works for me:
const [orientation, setOrientation] = useState(
ScreenOrientation.Orientation.PORTRAIT_UP
);
useEffect(() => {
// set initial orientation
ScreenOrientation.getOrientationAsync().then((info) => {
setOrientation(info.orientation);
});
// subscribe to future changes
const subscription = ScreenOrientation.addOrientationChangeListener((evt) => {
setOrientation(evt.orientationInfo.orientation);
});
// return a clean up function to unsubscribe from notifications
return () => {
ScreenOrientation.removeOrientationChangeListener(subscription);
};
}, []);
You should set your orientation field as default in your app.json / app.config.js. The app is locked to the specified orientation if this field is set to another value.
Related doc is here:
https://docs.expo.dev/versions/v46.0.0/config/app/#orientation
This is the line that doesn't do anything. Broken, bugged, POS? All of the above?
ScreenOrientation.addOrientationChangeListener((e) => {
console.log(e);
});
I had this same issue. The listener function was never firing.
Adding expo-sensors to my project seems to have fixed the callback for me. I think expo-screen-orientation might depend on expo-sensors
Steps for adding:
npx expo install expo-sensors
Rebuild your expo development client. (For me that command is eas build --profile simulator, but that will depend on your eas config)
After that, the listener callback function started firing.
Here's a code snippet of where I add the listener:
useEffect(() => {
ScreenOrientation.addOrientationChangeListener((e) => {
console.log(e)
})
}, [])
You're using the wrong package.
From the expo-screen-orientation docs:
Screen Orientation is defined as the orientation in which graphics are painted on the device. ... For physical device orientation, see the orientation section of Device Motion.