I have a button on my page that prompts an alert. If that user selects Yes, I then want the exit() function to run. However, the way it is coded now, for some reason nothing happens.
Does anyone know what I am doing wrong?
import React, { Component } from 'react';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, Text, StyleSheet, View, TextInput, Alert } from 'react-native';
type Props = {};
export default class IDScreen extends Component<Props> {
static navigationOptions = {
title: 'Identification',
};
exit = async () => {
alert("I should see this but I don't");
await AsyncStorage.clear();
this.props.navigation.navigate('Login');
}
promptExit() {
Alert.alert("Are you sure?", "You can't be serious.", [
{text: 'Yes, Sign out', onPress: async () => this.exit },
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
],
{ cancelable: true });
}
render() {
return (
<View style={styles.container}>
<Text style={styles.footerText} onPress={this.promptExit}>Sign Out</Text>
</View>
);
}
}
Try This method it Will Work
Invoke Alert.alert() function from Button, instead of calling Inside of another function, It will work, just see the code snippet.
And exit is an arrow function invoke like this "this.exit()" instead of this.exit.
import React, { Component } from 'react';
import {
ActivityIndicator,
AsyncStorage,
Button,
StatusBar,
Text,
StyleSheet,
View,
TextInput,
Alert } from 'react-native';
type Props = {};
export default class IDScreen extends Component<Props> {
static navigationOptions = {
title: 'Identification',
};
exit = async () => {
alert("I should see this but I don't");
await AsyncStorage.clear();
this.props.navigation.navigate('Login');
}
render() {
return (
<View style={styles.container}>
<Text style={styles.footerText}
onPress={
() => Alert.alert(
"Are you sure?", "You can't be serious.",
[
{text: 'Yes, Sign out', onPress: async () => this.exit() },
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'),
style: 'cancel'},
],
{ cancelable: true });
}
}>Sign Out</Text>
</View>
);
}
}
You need to modify promptExit() to an arrow function promptExit = () =>.
Arrow functions are used, not to redefine the value of this , inside their body, it simply means same thing within the function body as it does outside of it.
Since the function is called without its reference to a particular object, like yourObj.yourMethod(), therefore you either need to bind it in the class constructor / render or use arrow function.
Without it , it would lose it's context and will always be undefined or a global object.
Similarly, you can also read
When not to use arrow functions
Related
Can anyone tell me what I am doing wrong here. I am trying to fetch cities using API but componentDidMount nor componentWillMount is working.
I have tested my getWeather function using button, the function is working but when I try to call the it using componentDidMount or componentWillMount it is not working...
My code below:
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Header from './Header';
import { TextInput, Card, Button, Title } from 'react-native-paper';
import { useState } from 'react';
import { FlatList } from 'react-native-gesture-handler';
export default function Home() {
const [info, setInfo] = useState([{
city_name: "loading !!",
temp: "loading",
humidity: "loading",
desc: "loading",
icon: "loading"
}]);
getWeather = () => {
console.log("Hello Weather");
fetch("https://api.openweathermap.org/data/2.5/find?q=London&units=metric&appid={MY_API_KEY}")
.then(res => res.json())
.then(data => {
console.log(data);
/*setInfo([{
city_name: data.name,
temp: data.main.temp,
humidity: data.main.humidity,
desc: data.weather[0].description,
icon: data.weather[0].icon}]);
*/
})
}
componentWillMount = () => {
console.log("Hello Will");
this.getWeather();
}
componentDidMount = () => {
console.log("Hello Did");
this.getWeather();
}
return (
<View style={styles.container}>
<Header title="Current Weather"/>
<Card style = {{margin: 20}}>
<View>
<Title>{info.city_name}</Title>
<Title>{info.desc}</Title>
</View>
</Card>
<Button onPress={() => this.getWeather()} style={{margin: 40, padding: 20}}>Testing</Button>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
componentDidMount and componentWillMount only work in class based React components; what you have here is a functional component. You can use the useEffect hook to accomplish the same.
useEffect(() => {
getWeather();
}, []);
Note that this does not exist in functional components; you can just call the function directly after you have declared it.
If you haven't used useEffect before, you may have questions about the array as the second argument. If it is empty, it will run on mount and will run what you return from the first argument on unmount. If you want to run your effect again, add an dependencies into the array.
ComponentDidMount would only work in class components. Using the useEffect React hook would achieve the same effect without issues
I am coding a simple search input component for an app that will eventually become larger, but I am at a loss for why the onChange prop associated with it isn't being called. Here I will show my search input component and the app component into which I import it:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class SearchInput extends Component {
static defaultProps = {
onChange: () => Promise.resolve(),
}
static propTypes = {
onChange: PropTypes.func,
value: PropTypes.string,
}
render() {
const { value } = this.props;
return (
<input className="search-input" type='text' onChange={this.handleChange} value={value}/>
)
}
handeChange = (e) => {
const { onChange } = this.props;
onChange(e);
}
}
And then here's my main app component (very simple still, and keep in mind that I have list-rendering functionality, but that isn't where my issue lies). I'm pretty sure the issue lies somewhere in the handleSearchDidChange method that I wrote up and tacked onto the onChange prop for the SearchInput component:
import React, { Component } from 'react';
import Container from './components/container'
import List from './components/list'
import SearchInput from './components/search-input';
// Styles
import './App.css';
export default class App extends Component {
constructor(props){
super(props)
this.state = {
searchValue: undefined,
isSearching: false,
}
// this.handleSearchDidChange = this.handleSearchDidChange.bind(this);
}
render() {
// in the main render, we render the container component (yet to be styled)
// and then call renderList inside of it. We need "this" because this is
// a class-based component, and we need to tell the component that we are
// using the method associated with this class
return (
<div className="App">
<Container>
{this.renderSearchInput()}
{this.renderList()}
</Container>
</div>
);
}
renderSearchInput = () => {
const { searchValue } = this.state;
return (<SearchInput onChange={this.handleSearchDidChange} value={searchValue}/>)
}
renderList = () => {
// return the list component, passing in the fetchData method call as the data prop
// since this prop type is an array and data is an array-type prop, this is
// acceptable
return <List data={this.fetchData()}/>
}
// possibly something wrong with this method?
handleSearchDidChange = (e) => {
const { target } = e;
const { value } = target;
this.setState({
searchValue: value,
isSearching: true,
});
console.log('value: ', value);
console.log('searchValue: ', this.state.searchValue);
console.log('-------------------------')
}
fetchData = () => {
// initialize a list of items
// still wondering why we cannot put the listItems constant and the
// return statement inside of a self-closing setTimeout function in
// order to simulate an API call
const listItems = [
{title: 'Make a transfer'},
{title: 'Wire money'},
{title: 'Set a travel notice'},
{title: 'Pop money'},
{title: 'Edit travel notice'},
{title: 'test money things'},
{title: 'more test money things'},
{title: 'bananas'},
{title: 'apples to eat'},
{title: 'I like CocaCola'},
{title: 'Christmas cookies'},
{title: 'Santa Claus'},
{title: 'iPhones'},
{title: 'Technology is amazing'},
{title: 'Technology'},
{title: 'React is the best'},
];
// return it
return listItems;
}
You have a typo! Missing the "l" in handleChange :)
handleChange = (e) => {
const { onChange } = this.props;
onChange(e);
}
i run your code in sandBox:
https://codesandbox.io/s/onchange-problem-37c4i
there is no issue with your functionality as far as i can see.
but in this case if onChange dose not work for you is because maybe inside of < SearchInput /> component you don't pass the value up to the parent element.
check the sandBox and notice to the SearchInput1 and SearchInput2
I am trying when the user clicks on bottomTabNavigator the component screen will reload. I mean in my first component screen "AnotherA.js", I am using textinput which store user entered data in async storage and in another component "AnotherB.js" I am using get() of async storage to show my stored data on the screen. I am able to see the stored data the first time while reloading the whole app.
I am trying to get data without reloading, the whole app, by navigating with bottomTabNavigator it displays immediately.
//App.js
import React, { Component } from "react";
import { createAppContainer } from 'react-navigation';
import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs';
import { TabNavigator } from 'react-navigation';
import AnotherA from './AnotherA';
import AnotherB from './AnotherB';
const AppNavigator = createMaterialBottomTabNavigator(
{
AnotherA: { screen: AnotherA },
AnotherB: { screen: AnotherB }
},
{
initialRouteName: 'AnotherA',
activeColor: '#f0edf6',
inactiveColor: '#3e2465',
barStyle: { backgroundColor: '#694fad' },
pressColor: 'pink',
},
{
//tabBarComponent: createMaterialBottomTabNavigator /* or TabBarTop */,
tabBarPosition: 'bottom',
defaultnavigationOptions: ({ navigation }) => ({
tabBarOnPress: (scene, jumpToIndex) => {
console.log('onPress:', scene.route);
jumpToIndex(scene.index);
},
}),
}
);
const AppContainer = createAppContainer(AppNavigator);
export default AppContainer;
//AnotherA.js
import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from './styles';
export default class AnotherA extends Component {
constructor(props) {
super(props);
this.state = {
myKey: '',
text1: '',
}
}
async getKey() {
try {
//const value = await AsyncStorage.getItem('#MySuperStore:key');
const key = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: key,
});
} catch (error) {
console.log("Error retrieving data" + error);
}
}
async saveKey(text1) {
try {
await AsyncStorage.setItem('#MySuperStore:key', text1);
} catch (error) {
console.log("Error saving data" + error);
}
}
async resetKey() {
try {
await AsyncStorage.removeItem('#MySuperStore:key');
const value = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: value,
});
} catch (error) {
console.log("Error resetting data" + error);
}
}
componentDidMount() {
this.getKey();
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Enter Data"
value={this.state.myKey}
onChangeText={(value) => this.setState({ text1: value })}
multiline={true}
/>
<Button
onPress={() => this.saveKey(this.state.text1)}
title="Save"
/>
<Button
//style={styles.formButton}
onPress={this.resetKey.bind(this)}
title="Reset"
color="#f44336"
accessibilityLabel="Reset"
/>
</View>
)
}
}
//AnotherB.js
import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from './styles';
export default class AnotherB extends Component {
constructor(props) {
super(props);
this.state = {
myKey: '',
text1: '',
}
}
async getKey() {
try {
//const value = await AsyncStorage.getItem('#MySuperStore:key');
const key = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: key,
});
} catch (error) {
console.log("Error retrieving data" + error);
}
}
componentDidMount() {
this.getKey();
}
render() {
//const { navigate } = this.props.navigation;
//const { newValue, height } = this.state;
return (
<View style={styles.container}>
<Text>{this.state.myKey}</Text>
</View>
)
}
}
Please suggest, I am new to React-Native.
The issue is that you are retrieving the value from AsyncStorage when the component mounts. Unfortunately that isn't going to load the value on the screen when you switch tabs. What you need to do is subscribe to updates to navigation lifecycle.
It is fairly straight forward to do. There are four lifecycle events that you can subscribe to. You can choose which of them that you want to subscribe to.
willFocus - the screen will focus
didFocus - the screen focused (if there was a transition, the transition completed)
willBlur - the screen will be unfocused
didBlur - the screen unfocused (if there was a transition, the transition completed)
You subscribe to the events when the component mounts and then unsubscribe from them when it unmounts. So when the event you have subscribed to happens, it will call the function that you have put into the subscriber's callback.
So you can do something like this in you AnotherB.js:
componentDidMount() {
// subscribe to the event that we want, in this case 'willFocus'
// when the screen is about to focus it will call this.getKey
this.willFocusSubscription = this.props.navigation.addListener('willFocus', this.getKey);
}
componentWillUnmount() {
// unsubscribe to the event
this.willFocusSubscription.remove();
}
getKey = async () => { // update this to an arrow function so that we can still access this, otherwise we'll get an error trying to setState.
try {
const key = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: key,
});
} catch (error) {
console.log("Error retrieving data" + error);
}
}
Here is a quick snack that I created showing it working, https://snack.expo.io/#andypandy/navigation-life-cycle-with-asyncstorage
You can try to add then after getItem
AsyncStorage.getItem("#MySuperStore:key").then((value) => {
this.setState({
myKey: value,
});
})
.then(res => {
//do something else
});
When this component loads, the startSync function starts. However, I also have an exit function that navigates to a login screen if pressed during any of this.
What happens though is, if I press the exit button, it brings me back to the login page. However, the async function is still running so when it finishes it will then navigate me to the Identification screen.
I was wondering if there is a way to cancel all Async function's so that nothing is running in the background after the exit button is pushed.
import React, { Component } from 'react';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, Text, StyleSheet, View, } from 'react-native';
import * as pouchDB_helper from '../utils/pouchdb';
type Props = {};
export default class SyncScreen extends Component<Props> {
startSync = async () => {
pouchDB_helper.sync().then((response) => {
AsyncStorage.setItem('initial_sync', 'true');
//navigate to the identification page
this.props.navigation.navigate('Identification');
}, (error) => { Alert.alert("Error", "Syncing failed. Please try again."); });
}
exit = async () => {
await AsyncStorage.clear();
this.props.navigation.navigate('Login');
}
componentDidMount() {
this.startSync();
}
static navigationOptions = {
title: 'Syncing Settings',
};
render() {
return (
<View style={styles.container}>
<Text style={styles.footerText} onPress={this.exit}>Exit</Text>
</View>
);
}
}
What I am trying to do is alert the company_id that is in local storage.
import React, { Component } from 'react';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, Text, StyleSheet, View, } from 'react-native';
import * as pouchDB_helper from '../utils/pouchdb';
type Props = {};
export default class HomeScreen extends Component<Props> {
render() {
AsyncStorage.getItem('company_id', (err, result) => {
alert(result);
});
return (
<View style={styles.container}>
<Button title="Hi" onPress={this.doSomething} />
</View>
);
}
}
The following code works but I want to be able to do it from inside a helper function. If you see at the top, I have import * as pouchDB_helper from '../utils/pouchdb';
In there I have the following:
import React from 'react';
import { AsyncStorage } from 'react-native';
import PouchDB from 'pouchdb-react-native'
export async function pouchDB_config() {
return AsyncStorage.getItem('company_id', (err, result) => {
return result;
});
}
Instead of AsyncStorage.getItem() code, if I do alert(pouchDB_helper.pouchDB_config()) I get an object with the following: {"_40":0,"_65":0,"_55"_null,"72":null}
I know I'm obviously not doing something right with the whole asynchronous nature of it all so if anyone has any guidance I would greatly appreciate it. I'm still not up to par with how to work with async functions in react native.
This is beacause when you call the function pouchDB_helper.pouchDB_config() it returns a promise.
There are different ways to use this to your advantage.
In your util/pouchdb change the function as following:
export async function pouchDB_config() {
return await AsyncStorage.getItem('company_id');
}
Now you can call this function as follows:
pouchDB_config().then((company_id) => {
console.log(company_id);
});
Or you can call it anywhere else within an async function:
const otherAsyncFunction = async () => {
const company_id = await pouchDB_config();
console.log(company_id);
}