React Native, running an Alert on Startup of App - react-native

Building an internal company app, I need to ask a question before the app renders to determine fields.
I have this code.
useEffect(() => {
if (startup) {
console.log('Display Alert');
{
createTwoButtonAlert;
}
}
}, []);
For my useEffect, then here is my alert
const createTwoButtonAlert = () =>
Alert.alert('Title', 'Here is my Question?', [
{
text: 'Yes',
onPress: () => {
setQuestion(false), setStartup(false);
},
},
{
text: 'No',
onPress: () => {
setQuestion(true), setStartup(false);
},
},
]);
This alert is not displaying on startup with the current code.

Try putting the alert code directly inside useEffect inside the root (App) component. It will run only once when the component mounts.
useEffect(() => {
Alert.alert('Title', 'Here is my Question?', [{
text: 'Yes',
onPress: () => {
setQuestion(false), setStartup(false);
},
},
{
text: 'No',
onPress: () => {
setQuestion(true), setStartup(false);
},
},
]);
}, [])

Ok, while Grabriel's response did work. This was one of those stupid mistakes.
I forgot to inclose my alert in {}
a simple fix.
const createTwoButtonAlert = () => {
Alert.alert('Title', 'Here is my Question?', [
{
text: 'Yes',
onPress: () => {
setQuestion(false), setStartup(false);
},
},
{
text: 'No',
onPress: () => {
setQuestion(true), setStartup(false);
},
},
]);
}

Related

react native redirect to the settings update OS

Hey so i need to check if the user device is older version
if yes i will show alert that tell to update
and if press on button "UPDATE"
i want to take to the screen of the OS to UPDATE.
thanks for anyone who can help!
export const CheckOsVersion: FC = () => {
useEffect(() => {
const currentOS = Platform.OS;
const currentVersion = Number(Platform.Version);
const LATEST_VERSION_ANDROID = 34;
const LATEST_VERSION_IOS = 13;
const MAX_DIFF_VERSION = 2;
if (currentOS === 'android') {
if (LATEST_VERSION_ANDROID - currentVersion > MAX_DIFF_VERSION) {
Alert.alert(
'text',
'“text.',
[
{
text: 'NOT NOW',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'Update',
onPress: () => console.log('Update Pressed'),
},
],
{ cancelable: false },
);
}
} else if (currentOS === 'ios') {
if (LATEST_VERSION_IOS - currentVersion > MAX_DIFF_VERSION) {
Alert.alert(
'text',
'“text.',
[
{
text: 'NOT NOW',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'Update',
onPress: () => console.log('Update Pressed'),
},
],
{ cancelable: false },
);
}
}
}, []);
so the solution that i found is that you need to write a bridge in native
and use that
something like : Limk
there is example too here and they explain what is it in Kotlin
that what i did in the
File: SettingsUpdateModule.kt
package com.att.fn.android.missioniq.modules.settingsRedirect
import android.content.Intent
import androidx.core.content.ContextCompat.startActivity
import com.facebook.react.bridge.*
class SettingsUpdateModule(private val reactContext: ReactApplicationContext): ReactContextBaseJavaModule() {
override fun getName(): String = SettingsUpdateModule::class.java.simpleName
#ReactMethod
public fun updateOs() {
val i =Intent("android.settings.SYSTEM_UPDATE_SETTINGS",)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(this.reactContext, i, null);
}
}

how to navigation when onpress inside an alert

i trying to make a navigation to another screen when press a button on alert but i keep getting erro " [Error: TransformError SyntaxError: D:\one\HomeScreen.js: Unexpected token, expected "," (63:82) "
below is my code
please help me thank you guys
some random words so i can post this question
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
input: {
username: null,
email: null,
password: null,
confirm_password: null,
},
errors: {
username: null,
email: null,
password: null,
confirm_password: null,
},
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit = (event) => {
//event.preventDefault();
if (this.validate()) {
alert('ok');
console.log(this.state);
this.setState((prevState) => {
let input = Object.assign({}, prevState.input);
input.username = null;
input.password = null;
input.email = null;
input.confirm_password = null;
return { input };
});
this.setState((prevState) => {
let errors = Object.assign({}, prevState.errors);
errors.username = null;
errors.password = null;
errors.email = null;
errors.confirm_password = null;
return { errors };
});
Alert.alert('Đã Đăng Ký',
'Xin Hãy Đăng Nhập',
[
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style={styles.container}},
{text: 'OK', onPress: () => this.props.navigation.navigate('List'), //code to navigate}
],
{ cancelable: false });
}
}
Nvm i did it just remove one "," here is code in alert
Alert.alert('Đã Đăng Ký',
'Xin Hãy Đăng Nhập',
[
{text: 'Thoat', onPress: () => console.log('Cancel Pressed')},
// {text: 'OK', onPress: () => this.props.navigation.navigate('List'), //code to navigate}
{text: 'Tien Len', onPress: () => this.props.navigation.navigate('List')}
],
{ cancelable: false });

React native buttons.slice is not a function

I'm trying to print a variable using Alert.alert it might be me but I'm not able to do it Here's my code
const [reg, setRegion] = useState('');
Alert.alert(
"Confirm",
"this is just a " + {reg},
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{ text: "OK", onPress: () => console.log("OK Pressed") }
],
{ cancelable: false }
);
}
How can I print {reg} variable with a string?
If you getting this while using Alert in React native below solution worked for me.
Alert.alert("Error", "Enter an item", [{ text: "OK" }]);
const [reg, setRegion] = useState('');
Alert.alert(
"Confirm",
`this is just a ${reg}`,
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{ text: "OK", onPress: () => console.log("OK Pressed") }
],
{ cancelable: false }
);
}

WIX React Native Navigation: Show side drawer in tab based app

I am using React Native Navigation v2 from WIX in my RN project. For Dashboard(goToDahboard) stack I need to show hamburger icon on the left on on click show side drawer. How can this be implemented?
Since upgrading from v1, side menu options has changed and the docs aren't clear enough.
export const goToDashboard = () =>
Promise.all([
Icon.getImageSource('home', 22, '#272727'),
Icon.getImageSource('th-list', 22, '#272727'),
]).then(sources => {
Navigation.setRoot({
root: {
bottomTabs: {
children: [
{
stack: {
children: [
{
component: {
name: 'Dashboard',
},
},
],
options: {
bottomTab: {
icon: sources[0],
text: 'Dashboard',
},
},
},
},
{
stack: {
children: [
{
component: {
name: 'Settings',
},
},
],
options: {
bottomTab: {
icon: sources[1],
text: 'Settings',
},
},
},
},
],
id: 'bottomTabs',
},
},
});
});
export const goToAuth = () =>
Navigation.setRoot({
root: {
stack: {
id: 'Login',
children: [
{
component: {
name: 'Login',
},
},
],
},
},
});
I'am using like this, thats my code;
Navigation.setRoot({
root:{
sideMenu:{
left:{
component:{
name:'app.Main.SideDrawer'
}
},
center:{
bottomTabs:{
id: 'MainAppBottomTab',
children:[
{
stack:{
children:[
{
component:{
name: 'app.Main.Bottom_1',
options:{
bottomTab:{
text: "Bottom 1",
icon: require('./../../assets/images/Bottom_1.png'),
}
},
}
}
],
options: {
bottomTab: {
text: 'Bottom 1',
},
bottomTabs:{
backgroundColor: ColorTable.orange,
animate:false,
},
topBar:{
title:{
text: 'Bottom 1',
},
leftButtons:[
{
id: 'btn_toggle_drawer',
name: 'BTN_TOGGLE_DRAWER',
icon: require('./../../assets/images/hamburger_icon.png'),
}
],
}
}
}
}
]
}
}
}
}
});
Now we need to use wix's life cycle.
If you want to close it in SideDrawer, you should use the following code;
Navigation.mergeOptions(this.props.componentId, {
sideMenu: {
left: {
visible: false
}
}
});
this.props.componentId equal to app.Main.SideDrawer. Because of we are in app.Main.SideDrawer component.
If you want to open with hamburger icon, Go to whatever page you want to use for bottomTab, in our example I said Bottom_1.
Don't forget to type Navigation.events().bindComponent(this) into the constructor method. This allows you to linking with native.
Only the following command will work;
navigationButtonPressed({buttonId}) {
if (buttonId === "btn_toggle_drawer") {
Navigation.mergeOptions(this.props.componentId, {
sideMenu: {
left: {
visible: true
}
}
});
}
}
The code above works but is problematic. You're going to tell me that I'm going to have to press twice to turn it off =)
The solution is to use redux. Or mobx whichever you prefer.
To solve this problem, I used redux and redux-thunk.
Wix's is life cycle, please explore it: https://wix.github.io/react-native-navigation/#/docs/Usage?id=screen-lifecycle
With redux solution
Real function is;
navigationButtonPressed({buttonId}) {
if (buttonId === "btn_toggle_drawer") {
this.props.toggleDrawer(this.props.isSideDrawerVisible);
Navigation.mergeOptions(this.props.componentId, {
sideMenu: {
left: {
visible: this.props.isSideDrawerVisible
}
}
});
}
}
toggle_drawer action
export const toggleDrawer = (visible) => {
return (dispatch) => {
(visible) ? visible = true : visible = false;
dispatch({
type: TOGGLE_DRAWER,
payload: visible
});
}
};
toggle_drawer reducer
const INITIAL_STATE = {
isSideDrawerVisible: true
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case TOGGLE_DRAWER:
return {...state, isSideDrawerVisible: action.payload};
default:
return state;
}
}
Sample connect function;
import {connect} from "react-redux";
// actions
import {toggleDrawer} from "../../../actions/toggle_drawer";
const mapStateToProps = state => {
return {
isSideDrawerVisible: state.toggleDrawer.isSideDrawerVisible,
}
};
export default connect(mapStateToProps, {toggleDrawer})(Bottom_1_Screen);
Don't forget to connect wix with Redux. https://wix.github.io/react-native-navigation/#/docs/third-party?id=redux
I hope I can help you, I saw it a little late.
Have a nice day..
You can use
Navigation.mergeOptions()
like this to fire and open the drawer:
navigationButtonPressed = ({ buttonId }) => {
const { componentId } = this.props;
if (buttonId === 'sideMenu') {
Navigation.mergeOptions(componentId, {
sideMenu: {
left: {
visible: true,
},
},
});
}
}

Alert in react native

I am setting error in state true/false and if error = true then want to show alert
So i did this.
constructor() {
super()
this.state = {
email: "",
password: "",
error: false
}
this.handleSignUp = this.handleSignUp.bind(this)
}
and function
handleSignUp() {
fetch('http://myIp:9999/signUp', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(this.state),
})
.then((res) => {
console.log("here")
console.log(res)
this.setState({error: false})
}).catch((e) => {
if (e) {
console.log('e')
console.log(e.status)
this.setState({error: true})
}
})
}
and render method as
render() {
var alert1 = alert(
"User exist",
"User with same Email exist. Try some to login or use other Email",
[
{text: "Ok", style: 'cancle', onPress: () => this.setState({error: false})}
]
)
return (
<View style={styles.container}>
{this.state.error ? alert1 : ""}
<Header function1={() => this.props.navigation.openDrawer()}/>
....
</View>
)
}
and the result is no matter if error is true or false when i open this screen then alert appears and then error
so I change alert1.
var alert1 = (<View>
alert(
"User exist",
"User with same Email exist. Try some to login or use other Email",
[
{text:"Ok",style:'cancle',onPress:()=> this.setState({error:false})}
]
)
</View>)
and now error is resolved but on screen load alert is appearing.
handleSignUp() {
fetch('http://myIp:9999/signUp', {
...
})
.then((res) => {
//insted of this line => this.setState({error: false}) call Alert directly
Alert.alert(
'Alert Title',
'My Alert Msg',
[
{text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
{text: 'OK', onPress: () => console.log('OK Pressed')},
],
{ cancelable: false }
)
})
}