I am trying to print text content of login.php into the screen via "var result", but the fetch function won't alter value of "var result". How can I set value of result from output of the fetch function?
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
StatusBar,
} from 'react-native';
import Logo from '../components/Logo';
import Form from '../components/Form';
import loginapi from '../apis/loginapi';
var result='noresult';
export default class Login extends Component<{}> {
render() {
login();
return (
<View style={styles.container}>
<Logo/>
<Form/>
<Text>
{result}
</Text>
<Text>
</Text></View>
);
}
}
function login() {
result = fetch('https://www.skateandstrike.com/loginsv/login.php').then((text) => {return text;});
}
const styles = StyleSheet.create({
container : {
backgroundColor:'#f05545',
flex: 1,
alignItems:'center',
justifyContent:'center',
}
});
function myFunction() {
this.setState({ showLoading: false });
}
This is not working too, using setState:
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
StatusBar,
} from 'react-native';
import Logo from '../components/Logo';
import Form from '../components/Form';
import loginapi from '../apis/loginapi';
export default class Login extends Component<{}> {
constructor(){
super();
this.state = {
data:'NoData',
}
}
render() {
login();
return (
<View style={styles.container}>
<Logo/>
<Form/>
<Text>
{this.state.data}
</Text>
</View>
);
}
}
function login() {
fetch('https://www.skateandstrike.com/loginsv/login.php').then(data => this.setState(data));
}
const styles = StyleSheet.create({
container : {
backgroundColor:'#f05545',
flex: 1,
alignItems:'center',
justifyContent:'center',
}
});
function myFunction() {
this.setState({ showLoading: false });
}
Am I using setState in a wrong way? Thanks in advance for your help.
When using the fetch API, I'd recommend using a promise, and you parse it if you are setting the state.
React re-renders on state/props change.
sample code:
fetch(url)
.then(data => data.json()) // if needed
.then(data => this.setState(data))
remember to set state in the constructor.
Related
I have two components. One is the provider and the second is a child. Now I want to use the function of provider in the child but with my current approach, it says that function is undefined. Can you see what I'm doing wrong?
Here is the code below.
import React from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
const MyProvider = (props) => {
const { children } = props;
const handlePress = () => {
console.log("Provider component function called!");
};
return (
<View>
{children}
</View>
);
};
const NoLocationAccess = (props) => {
const { handlePress } = props;
console.log("handlePress : ",handlePress)
return (
<TouchableOpacity onPress={handlePress}>
<Text>I am the child component</Text>
</TouchableOpacity>
);
};
export default NoLocationAccess;
I have tried provider.wrapper. that made things more problematic.
To call a function, that is defined in the provider, from the child you need too pass it down as a prop.
Here the modified Code:
import React from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
const MyProvider = (props) => {
const { children } = props;
const handlePress = () => {
console.log("Provider component function called!");
};
return (
<View>
{React.Children.map(children, (child) => {
return React.cloneElement(child, { handlePress });
})}
</View>
);
};
const NoLocationAccess = (props) => {
const { handlePress } = props;
console.log("handlePress : ",handlePress)
return (
<TouchableOpacity onPress={() => handlePress()}>
<Text>I am the child component</Text>
</TouchableOpacity>
);
};
export default NoLocationAccess;
Try it
It took me a while. but I have done this high-order component. this idea came to mind with the redux connect method. so took that approach and created a higher-order component. that works flawlessly.
Here is the solution.
High-Order Component.
import React from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
const MyProvider = (props) => {
class GPSComponent extends React.Component {
componentDidMount() {
}
requestPermissions= async()=> {
console.log("i is called",this.props.userCurrentLocation)
}
render() {
return <WrappedComponent
requestPermissions={this.requestPermissions}
{...this}
/>;
}
}
return GPSComponent;
};
child component.
import React from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
import MyProvider from "./MyProvider"
const NoLocationAccess = (prop) => {
const { requestPermissions } = prop;
console.log("requestPermissions ",requestPermissions)
return (
<TouchableOpacity onPress={requestPermissions}>
<Text>I am the child component</Text>
</TouchableOpacity>
);
};
export default MyProvider(NoLocationAccess);
Trying to load a splash screen for a set amount of time but error reads ReferenceError: Can't find variable: SetTimeout.
import React, { Component } from 'react';
import { Image, View } from 'react-native';
import { inject } from 'mobx-react';
#inject("stores")
export default class SplashScreen extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
const { stores, navigation } = this.props;
SetTimeout (() => {
navigation.navigate("Login")
}, stores.config.SplashTime)
}
render() {
const { stores } = this.props
return (
<View style={{flex: 1}}>
<Image style={{flex: 1, width: null, height: null}} source={stores.config.SplashIMG}/>
</View>
)
}
}
The spelling for setTimeout is incorrect as SakoBu pointed out! Method names are case sensitive. Also try window.setTimeout if that does not fix the problem.
I have a TypeForm integrated with my app and this type form opens in a WebView. The process goes like when I Sign up, a type form opens in a WebView. On form submit I want it to be redirected to home screen.
Here is my code:
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
ScrollView,
WebView,
Linking
} from 'react-native';
import Constants from '../constants';
import NavigationBar from 'react-native-navbar';
import Icon from 'react-native-vector-icons/FontAwesome';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as userActions from '../redux/modules/user';
type Props = {};
class Typeform extends Component<Props> {
constructor(props){
super(props);
this.state={
}
// console.log('props ******* next_lottery_time constructor ******** ',props)
}
render() {
const { navigate, goBack } = this.props.navigation;
const titleConfig = {
title: 'SURVEY',
tintColor:Constants.Colors.White
};
const uri = 'https://threadest1.typeform.com/to/vjS2Nx';
return (
<View style={{flex:1}}>
<NavigationBar
title={titleConfig}
style={{backgroundColor: 'rgb(32,73,157)'}}
statusBar={{hidden:false,tintColor:'rgb(32,73,157)'}}
leftButton={<TouchableOpacity style={{marginLeft:Constants.BaseStyle.DEVICE_WIDTH/100*2.5,marginTop:Constants.BaseStyle.DEVICE_HEIGHT/100*.8}} onPress={()=>goBack()}><Icon color={Constants.Colors.White} name='chevron-circle-left' size={30} /></TouchableOpacity>} />
<WebView
ref={(ref) => { this.webview = ref; }}
source={{ uri }}
onNavigationStateChange={(event) => {
if (event.url !== uri) {
this.webview.stopLoading();
Linking.openURL(event.url);
}
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
//justifyContent: 'center',
alignItems: 'center',
}
});
const mapDispatchToProps = dispatch => ({
userActions: bindActionCreators(userActions, dispatch)
});
export default connect(null, mapDispatchToProps)(Typeform);
I am using react-navigation for screen navigation purpose.
This all you can do it in on navigation state change so when you submit from that will return an response and that response you can capture and on that condition you can navigate to another screen.
i my scenario i am using for payment with instamojo.
import React, { Component } from "react";
import { Text, View, StyleSheet, WebView } from "react-native";
import { BASE_URL } from "../../../constants/apiList";
import SecondaryHeader from "../../common/SecondaryHeader";
class Payment extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
refreshing: false,
isPiad: false,
packages: []
};
}
getParameterByName(name, url) {
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) {
return null;
}
if (!results[2]) {
return "";
}
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
onNavigationStateChange = eve => {
if (eve.loading !== this.state.isLoading) {
this.setState({
isLoading: eve.loading
});
}
if (eve.url.indexOf("api/orders/") > -1) {
this.props.navigation.replace("paymentStatus", {
url: eve.url,
id: this.props.navigation.state.params.id
});
}
};
render() {
return (
<View style={styles.container}>
<SecondaryHeader title="PAYMENT" {...this.props} />
<WebView
source={{ uri: this.props.navigation.state.params.url }}
onNavigationStateChange={this.onNavigationStateChange}
style={{ height: 200 }}
startInLoadingState={true}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
export default Payment;
so after payment instamojo will redirect to payment success of fail page that time i am capturing url and checking if success redirection is there then i am navigating to my payment status screen/
If you are using StackNavigator from react-navigation redirection or switch screens are really easy. you just need to call like the following code after your success response.
StackNavigator will look like
const Stacker = StackNavigator(
{
Landing: {
path: "Landing",
screen: LandingDrawer
}
},
{
initialRouteName: this.state.isLoggedIn,
headerMode: "none",
navigationOptions: {
headerVisible: false
}
}
);
Redirection
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName: "Landing"
})
]
});
this.props.navigation.dispatch(resetAction);
this is what I used in my app, hope this will help you
Have you looked at using the React wrapper around Typeform Embed SDK?
It seems to be the way to go for what you want to achieve.
You can listen to onSubmit event that will be triggered when the typeform is submitted and then do the redirection.
The code would look like this
import React from 'react';
import { ReactTypeformEmbed } from 'react-typeform-embed';
class App extends React.Component {
render() {
return <ReactTypeformEmbed url={'https://demo.typeform.com/to/njdbt5'} onSubmit='alert("form submitted");'/>
}
}
Hope it helps
Here I need to pass a one variable to HomeContainer.But when I click the GO TO ABOUT button I got above error.I'm new to React Native.So I'm not sure that I'm following correct method to pass data to another view.Hope someone will help me.Thanks in advance.
import React, { Component } from 'react'
import {
AppRegistry,
Navigator,
View
} from 'react-native'
import Router from './src/components/Router'
class navigation extends Component {
render() {
return (
<Navigator
initialRoute={{name: 'Router', component: Router, index: 0}}
renderScene={(route, navigator) => {
return React.createElement(route.component, { ...this.props, ...route.passProps, navigator, route } );
}} />
);
}
}
AppRegistry.registerComponent('navigation', () => navigation)
import React, { Component } from 'react'
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableHighlight,
TextInput
} from 'react-native'
import AboutContainer from './about/AboutContainer'
import HomeContainer from './home/HomeContainer'
export default class Router extends Component {
constructor(){
super()
}
getInitialState() {
return {}
}
_goToHome() {
this.props.navigator.push({
component: HomeContainer,
passProps: {
username: this.state.username,
}
})
}
updateUsername(username) {
this.setState({ username })
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight
onPress={ () => this._goToHome() }
style={ styles.button }>
<Text>
GO TO ABOUT
</Text>
</TouchableHighlight>
<TextInput
onChangeText={ (username) => this.updateUsername(username) }
placeholder="Your Username"
style={ styles.input }
/>
</View>
)
}
}
I need inside the file artistPage.js to refer to the TabNavigator in index.ios.js. In particular, I need to change the styles to hide the TabBar when the user is on the page artistPage.
How can I do that? Any ideas?
I tried to transfer styles in the props but there is the read-only mode(
index.ios.js
'use strict'
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
Image,
Text,
NavigatorIOS,
TouchableHighlight,
NavigationBar,
} from 'react-native';
import config from './config';
import ImagesList from './app/imagesList';
import TabNavigator from 'react-native-tab-navigator';
import Badge from './node_modules/react-native-tab-navigator/Badge'
class MyApp extends Component {
constructor(props) {
super(props);
this.state = {
selectedTab: 'images',
showTabBar: true
};
}
render() {
let tabBarStyle = {};
let sceneStyle = {};
if (this.state.showTabBar) {
tabBarStyle = styles.tabBar;
sceneStyle.paddingBottom = 54;
} else {
tabBarStyle.height = 0;
tabBarStyle.overflow = 'hidden';
sceneStyle.paddingBottom = 0;
}
return (
<View style={styles.container}>
<TabNavigator
tabBarStyle={ tabBarStyle }
sceneStyle={sceneStyle}
>
<TabNavigator.Item
titleStyle={styles.title}
selectedTitleStyle={styles.title_select}
selected={this.state.selectedTab === 'images'}
title="TATTOOS"
renderIcon={() => <Image source={require('./images/tabbar/tattoos_icon.png')} />}
renderSelectedIcon={() => <Image source={require('./images/tabbar/tattoos_icon_selected.png')} />}
onPress={() => this.setState({ selectedTab: 'images' })}>
<NavigatorIOS
style={styles.container}
initialRoute={{
title: 'MyApp',
component: ImagesList,
passProps: { showTabBar: true},
}}
navigationBarHidden={true}/>
</TabNavigator.Item>
</TabNavigator>
</View>
);
}
}
AppRegistry.registerComponent('MyApp', () => MyApp);
imageList.js
'use strict'
import React, { Component } from 'react';
import {
StyleSheet,
ListView,
View,
Text,
Image,
Dimensions,
ActivityIndicator,
TouchableHighlight,
RefreshControl
} from 'react-native';
import ArtistPage from './imageCard';
class ImagesList extends Component {
constructor(props) {
super(props);
this.state = {
};
}
_artistPage() {
this.props.navigator.push({
component: ArtistPage
});
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight
onPress={this._artistPage()}
>
<Text>Got to Next Page</Text>
</TouchableHighlight>
</View>
);
}
}
}
module.exports = ImagesList;
artistPage.js
'use strict'
import React, { Component } from 'react';
import {
StyleSheet,
Text,
ListView,
View,
TouchableHighlight,
Image,
} from 'react-native';
class ArtistPage extends Component {
constructor(props) {
super(props);
this.state = {
};
}
_backTo() {
this.props.navigator.pop();
}
render() {
return (
<View>
<TouchableHighlight style={{marginTop: 100, marginLeft: 50}} onPress={() => this._backTo()} >
<Text>Back {this.props.showTabBar.toString()}</Text>
</TouchableHighlight>
</View>
);
}
}
module.exports = ArtistPage;
Here is how to hide TabNavigator: https://github.com/exponentjs/react-native-tab-navigator
let tabBarHeight = 0;
<TabNavigator
tabBarStyle={{ height: tabBarHeight, overflow: 'hidden' }}
sceneStyle={{ paddingBottom: tabBarHeight }}
/>
But I don't understand how to access it from artistPage.js
Thank you!
Data flow in React is one way. What it means in practice is that, to change something that a certain component receives via props, it will need to call back into the parent component, via a function from props.
The React website has a nice intro to the concept.
In your particular case, you could have a tabBarVisible state in MyApp, and inside render, compute the style to apply to the tab bar.
MyApp also can have a method to change this state:
hideTabBar() {
this.setState({ tabBarVisible: true });
}
Now, in order to let ArtistPage toggle that, you can pass the hideTabBar function from MyApp to ArtistPage as a prop, and call it in ArtistPage in a lifecycle hook, like componentDidMount.