React Native - SetTimeout variable not found - javascript

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.

Related

navigation between component in react native

I need to navigate between two view in React Native. But the problem is my component where the button to navigate is on an other component. I use the react-navigation.
Let me show you :
I have my component MainPage here
class MainPage extends Component {
render() {
return <View style={styles.container}>
<ComponentWithButton />
</View>
}
}
So in my component ComponentWithButton :
class ComponentWithButton extends Component {
goToComponent(){
this.props.navigation.push('Next')
}
render() {
return <View style={styles.container}>
<Button onPress={this.goToComponent.bind(this)}/>
</View>
}
}
My next component is called NextComponent.
I have the error undefined is not an object (evaluating "this.props.navigation.push")
My stack navigator is this :
const RootStack = StackNavigator(
{
Main: {
screen: MainPage
},
Next: {
screen: NextComponent
}
},
{
initialRouteName: "Main"
},
{
navigationOptions: {
header: { visible: false }
}
}
);
I try to run my code with just one component it's working perfectly. I think there is problem because ComponentWithButton is not called in my RootStack or something like that. I don't know I am a newbie
you didn't pass the navigation props to the
<ComponentWithButton />
do something like this
<ComponentWithButton navigation={this.props.navigation}/>
also the method should be
this.props.navigation.navigate('Next')
if I recall
react-navigation has a function withNavigation that populate navigation props in any of your Component. Just use it like that:
import { withNavigation } from 'react-navigation';
class ComponentWithButton extends Component {
goToComponent(){
this.props.navigation.push('Next')
}
render() {
return <View style={styles.container}>
<Button onPress={this.goToComponent.bind(this)}/>
</View>
}
}
export default withNavigation(ComponentWithButton);

Variable won't be set inside the fetch function

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.

React Native : Why is "navigation" not being passed to my component?

I have been working on this problem for two days now and nothing on the web seems to be exactly what I am looking for.
I am attempting to implement a StackNavigator into my React Native app, but for some reason "navigation" is not being passed as a prop to the involved components. Therefore when I call this.props.navigation.navigator by pressing Button, I get the error undefined is not an object (evaluating this.props.navigation.navigate).
I have logged the props several times and the props object is empty, so the issue is not a deconstruction-of-the-props-object issue like others who get this error have had, but the fact that the navigation prop is not there in the first place.
I've tried placing the navigator code in its own file and in the App.js file thinking that it was somehow called after the components are rendered, and therefore not getting a chance to pass the navigation prop in, but that didn't work either. I've also looked to see if it is part of the props in the componentDidMount event. Still not.
import React, { Component } from 'react'
import { Text, View, Button, StyleSheet, FlatList } from 'react-native'
import { StackNavigator } from 'react-navigation'
import { getDecks } from '../utils/api'
import NewDeckView from './NewDeckView'
import DeckListItem from './DeckListItem'
export default class DeckListView extends Component {
constructor(props){
super(props)
this.state = {
decks: []
}
}
componentDidMount(){
console.log('props now test',this.props)
getDecks()
.then( result => {
const parsedResult = JSON.parse(result);
const deckNames = Object.keys(parsedResult);
const deckObjects = [];
deckNames.forEach( deckName => {
parsedResult[deckName].key = parsedResult[deckName].title
deckObjects.push(parsedResult[deckName])
})
this.setState({
decks:deckObjects
})
} )
}
render(){
return (
<View style={styles.container}>
<Text style={styles.header}>Decks</Text>
<FlatList data={this.state.decks} renderItem={({item})=><DeckListItem title={item.title} noOfCards={item.questions?item.questions.length:0}/>} />
<Button styles={styles.button} title="New Deck" onPress={()=>{this.props.navigation.navigate('NewDeckView')}}/>
</View>
)
}
}
const styles = StyleSheet.create({
header:{
fontSize:30,
margin:20,
},
container:{
flex:1,
justifyContent:'flex-start',
alignItems:'center'
},
button:{
width:50
}
})
const Stack = StackNavigator({
DeckListView : {
screen: DeckListView,
},
NewDeckView: {
screen:NewDeckView,
}
})
Like Vicky and Shubhnik Singh mentioned, you need to render the imported navigation stack in App.js like so:
import React from 'react';
import { Stack } from './navigator/navigator'
export default class App extends React.Component {
render() {
return <Stack/>
}
}
The navigator should look something like this and the first key in the object passed to StackNavigator will be rendered by default. In this case, it will be DeckListView.
import { StackNavigator } from 'react-navigation'
import DeckListView from '../components/DeckListView'
import NewDeckView from '../components/NewDeckView'
export const Stack = StackNavigator({
DeckListView : {
screen: DeckListView,
navigationOptions: {
headerTitle: 'Home',
},
},
NewDeckView: {
screen:NewDeckView,
navigationOptions: {
headerTitle: 'New Deck',
},
},
})
Thanks guys for the support! Somehow this wasn't clear for me in the documentation.

Reuse screen in React Navigation

I'm new to React Native and trying to set up a navigation between two screens (or pages) using react-navigation package. I'm using a StackNavigator right now.
The problem I am facing is that there seems to be no way to navigate back to a previous screen. All I can do is call navigate(). If, for example, I want to navigate from Home to FRW and back to Home, it seems this will leave me with two instances of Home on the stack that are executed in parallel (one of which can't be seen). My code is something like this:
app.js
import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { StackNavigator } from 'react-navigation';
import HomeScreen from './views/HomeScreen.js'
import FRWScreen from './views/FRWScreen.js'
const MainNavigator = StackNavigator({
FRW: { screen: FRWScreen },
Home: { screen: HomeScreen },
}, {
headerMode: 'screen',
headerVisible: false,
navigationOptions: {
header: null
},
initialRouteName: "Home"
});
export default class TestApp extends Component {
render() {
return (
<MainNavigator></MainNavigator>
);
}
}
AppRegistry.registerComponent('TestApp', () => TestApp);
HomeScreen.js
export default class HomeScreen extends Component {
static navigationOptions = {
title: 'Welcome'
};
(...)
onSomeButtonPressed() {
this.props.navigation.navigate('FRW');
}
componentDidMount() {
if (this.locationWatchID !== undefined) return;
this.locationWatchID = navigator.geolocation.watchPosition((position) => {
console.log(this.locationWatchID);
});
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this.locationWatchID);
}
render() {
(...)
return (
<View style={styles.container}>
<MapView ref={ref => { this.map = ref; }} />
<TouchableHighlight
style={styles.someButton}
onPress={this.onSomeButtonPressed.bind(this)}
>
<Text>Press Me</Text>
</TouchableHighlight>
</View>
)
}
}
FRWScreen.js looks similar to HomeScreen.js (and contains .navigate("Home"))
The result of this code is, after navigating to FRW and back, that the geolocation callback is executed twice with different watchIDs. Which makes me believe the HomeScreen is actually on the navigation stack twice.
On your FRWScreen you should use this.props.navigation.goBack(null) instead. See https://reactnavigation.org/docs/navigators/navigation-prop#goBack-Close-the-active-screen-and-move-back.

Exported Constant not working in stylesheet

In one of the components in my project, I export a constant integer and then use it as a value for height in StyleSheet. In one particular case, it is not working and I can't figure out why. I have extracted the minimum possible code to reproduce it.
In TopBar.js, I export NAVBAR_HEIGHT and import it in both Home.js and MyModal.js. While it works right in Home.js when I use it as value of height in StyeSheet, it doesn't work in MyModal.js. However, if I replace NAVBAR_HEIGHT with a hardcoded int value, it works. It also works if I use NAVBAR_HEIGHT inline instead of creating a StyleSheet and passing the styles.topbar object.
(I wanted to make an rnplay for this, but looks like it can't make multiple files and thus, I couldn't reproduce it.)
Here is the code, apologies for making it long. I've also pushed it to git here.
Home.js (root component)
import React from 'react';
import {
View, StyleSheet, TouchableHighlight
} from 'react-native';
import TopBar, { NAVBAR_HEIGHT } from './TopBar';
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = { showModal: false };
}
render() {
return (
<TouchableHighlight onPress={this.toggleModal}>
<View style={styles.view}>
<TopBar showModal={this.state.showModal}
onClose={this.toggleModal} />
</View>
</TouchableHighlight>
);
}
toggleModal = () => {
this.setState({ showModal: !this.state.showModal });
}
}
const styles = StyleSheet.create({
view: {
height: NAVBAR_HEIGHT,
backgroundColor: 'blue',
}
});
MyModal.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Modal,
Text,
} from 'react-native';
import { NAVBAR_HEIGHT } from './TopBar';
export default class MyModal extends Component {
render() {
return (
<Modal animationType={'slide'}
visible={this.props.visible}
style={styles.container}
onRequestClose={this.props.onClose}>
<View style={styles.topbar}>
<Text style={styles.text}>{NAVBAR_HEIGHT}</Text>
</View>
</Modal>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
topbar: {
backgroundColor: 'red',
height: NAVBAR_HEIGHT,
},
text: {
fontSize: 20
}
});
TopBar.js
import React, { Component } from 'react';
import {
View,
StyleSheet,
Platform,
Text,
} from 'react-native';
import MyModal from './MyModal';
export const NAVBAR_HEIGHT = Platform.OS === 'ios' ? 200 : 100;
export default class TopBar extends Component {
render() {
return (
<View style={styles.container}>
<Text>TEST</Text>
<MyModal visible={this.props.showModal}
onClose={this.props.onClose} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'green',
},
});
I might be making some silly mistake but I have spent way too much time on this one and I'm still clueless. Help.
The modules TopBar.js and MyModal.js have a circular dependency: TopBar imports MyModal, and MyModal imports TopBar. Because module resolution is synchronous, the imported value is undefined.
Extract the common dependency into its own module and reference it from both TopBar and MyModal.
Here's a simple reproduction:
a.js
import {b} from './b';
export const a = 'a';
console.log('A sees B as', b);
b.js
import {a} from './a';
export const b = 'b';
console.log('B sees A as', a);
main.js
import {a} from './a';
Outputs:
B sees A as undefined
A sees B as b

Categories