Setting TextInput value from AsyncStorage in React Native - react-native

I have successfully stored my email and password value in AsyncStorage in ReactNative.
Now, I am also able to fetch the values from AsyncStorage when application getting started.
I am displaying values using Alert.alert() right now.
I am confused that How can I set that values in my two TextInputs :
1. Email and 2. Password.
I have little bit idea about state. It might be possible using state.
But how ?
Any idea that How can I change or set the value in TextInput dynamically ?
Thanks.
EDIT
States :
state = {
email: '',
password: '',
register: false,
activity: false,
isRemember:false,
}
componentWillMount(){
//To handle Remember Me :
this._checkForRememberMe();
}
On Login Success :
this._storeRememberME();
_storeRememberME=async()=>{
//SAVING ASYNCSTORAGE VALUE FOR REMEMBER ME :
Alert.alert("is Remember state >>"+this.state.isRemember);
if(this.state.isRemember){
await AsyncStorage.setItem('username', this.state.email);
await AsyncStorage.setItem('password', this.state.password);
Alert.alert("is Remember state inside >>"+this.state.isRemember);
await AsyncStorage.setItem('isRemember', 'yes');
}else{
const isRemember =AsyncStorage.getItem('rememberMe');
if(isRemember){
Alert.alert("Async clear "+this.state.isRemember);
await AsyncStorage.clear();
}
}
}
// Fetch the token from storage then navigate to our appropriate place
_checkForRememberMe = async () => {
const isRemember = await AsyncStorage.getItem('isRemember');
if(isRemember){
const username = await AsyncStorage.getItem('username');
const password = await AsyncStorage.getItem('password');
this.state.email=username;
this.state.password=password;
this.state.checkedRemember=true;
Alert.alert(""+this.state.email+""+this.state.password);
}else{
this.state.checkedRemember=false;
}
}
_handleCheck(val) {
if(val){
this.state.isRemember=true;
}else{
this.state.isRemember=false;
}
Alert.alert("is remember", ">>>"+val);
}
checkbox is as below :
<Checkbox
onChange={(val) => this._handleCheck(val)}
style={{marginRight:8}}
checked={checkedRemember}
checkedColor={$primaryBlue}
uncheckedColor={$lightGray}
iconName='matMix'
/>

You can take a variable in your state & set this variable to your TextInput. Then in constructor set AsyncStorage value in your state. Because state are reflected to views. So when you get value from AsyncStorage then you will see value in TextInput.
A very good example for you.
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
Button,
View,
AsyncStorage
} from 'react-native';
export default class AsyncStorageExample extends Component {
constructor(props) {
super(props);
this.state = {
myKey: null
}
}
async getKey() {
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({myKey: value});
} catch (error) {
console.log("Error retrieving data" + error);
}
}
async saveKey(value) {
try {
await AsyncStorage.setItem('#MySuperStore:key', value);
} 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);
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to Demo AsyncStorage!
</Text>
<TextInput
style={styles.formInput}
placeholder="Enter key you want to save!"
value={this.state.myKey}
onChangeText={(value) => this.saveKey(value)}
/>
<Button
style={styles.formButton}
onPress={this.getKey.bind(this)}
title="Get Key"
color="#2196f3"
accessibilityLabel="Get Key"
/>
<Button
style={styles.formButton}
onPress={this.resetKey.bind(this)}
title="Reset"
color="#f44336"
accessibilityLabel="Reset"
/>
<Text style={styles.instructions}>
Stored key is = {this.state.myKey}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
padding: 30,
flex: 1,
alignItems: 'stretch',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
formInput: {
paddingLeft: 5,
height: 50,
borderWidth: 1,
borderColor: "#555555",
},
formButton: {
borderWidth: 1,
borderColor: "#555555",
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
marginTop: 5,
},
});
AppRegistry.registerComponent('AsyncStorageExample', () => AsyncStorageExample)

Related

To store multiple values of form using AsyncStorage

I need to store two values from a screen using AsyncStorage and also store it in the format of key value pairs.I want this data to be stored locally in the mobile and later retrieved from it when needed.
I have tried to retrieve single data but haven't been able to do with multiple data.
import React, { Component } from 'react';
import { StyleSheet, AsyncStorage, TextInput, View, Alert, Button, Text, TouchableOpacity } from 'react-native';
class FormData extends Component {
constructor(props){
super(props)
this.state = {
// myKey: '',
key: '',
text1: '',
text2: '',
getValue: '',
infoValue:''
};
}
savefunction = () => {
let storedObject = {};
storedObject.textval1 = text1;
storedObject.textval2 = text2;
try {
AsyncStorage.setItem('allTextValue', JSON.stringify(storedObject));
} catch (error) {
}
}
getfunction = () => {
try {
AsyncStorage.getItem('allTextValue').then((infoValue) => {
let resObject = JSON.parse(infoValue);
let textval1 = resObject.text1
let textval2 = resObject.text2
}).done();
} catch (error) {
}
}
render (){
return(
<View style={styles.MainContainer}>
<Text style= {styles.TextComponentStyle}>User Form</Text>
<TextInput
placeholder="Enter User Email"
onChangeText={(value) => this.setState({ text1: value})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Password"
onChangeText={(value) => this.setState({ text2: value})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<Button onPress={this.savefunction}
title="Save key" color="#2196F3" />
<Button onPress={this.getfunction}
title="Get key" color="#2196F3" />
<Text style={styles.text}> {this.state.getValue} </Text>
</View>
);
}
}
export default FormData;
const styles = StyleSheet.create({
MainContainer :{
justifyContent: 'center',
flex:1,
margin: 10,
},
TextInputStyleClass: {
textAlign: 'center',
marginBottom: 7,
height: 40,
borderWidth: 1,
// Set border Hex Color Code Here.
borderColor: '#2196F3',
// Set border Radius.
borderRadius: 5 ,
},
text: {
fontSize: 20,
textAlign: 'center',
},
TextComponentStyle: {
fontSize: 20,
color: "#000",
textAlign: 'center',
marginBottom: 15
}
});
I expect multiple data to be stored in the map with key value pair
You're not saving the price properly. You declare a status value and are putting a value into a variable with the same name. Code needs to be modified.
savefunction = () => {
let storedObject = {};
storedObject.textval1 = this.state.text1;
storedObject.textval2 = this.state.text2;
try {
AsyncStorage.setItem('allTextValue', JSON.stringify(storedObject));
} catch (error) {
}
}
...
getfunction = async () => {
try {
const infoValue = await AsyncStorage.getItem('allTextValue')
let resObject = JSON.parse(infoValue);
let textval1 = resObject.textval1
let textval2 = resObject.textval2
console.log(textval1);
console.log(textval2);
} catch (error) {
console.log(error);
}
}
The only part i see a problem is where you get the values from the object when you get the items:
let resObject = JSON.parse(infoValue);
let textval1 = resObject.textval1
let textval2 = resObject.textval1
You can also change it to
let resObject = JSON.parse(infoValue);
let {textval1, textval2} = resObject

How to make a QR code scanner in React native using expo?

When I run https://snack.expo.io/#sushil62/qr-code-scanner in the expo which works fine, but when copy the same code given in App.js file, after running the application the camera opens but it shows no result while scanning, and
in expo also when changing the snack version 33 or higher it does not work there too.
import React, { Component } from 'react';
import { Alert, Linking, Dimensions, LayoutAnimation, Text, View, StatusBar, StyleSheet, TouchableOpacity } from 'react-native';
import { BarCodeScanner, Permissions } from 'expo';
export default class App extends Component {
state = {
hasCameraPermission: null,
lastScannedUrl: null,
};
componentDidMount() {
this._requestCameraPermission();
}
_requestCameraPermission = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({
hasCameraPermission: status === 'granted',
});
};
_handleBarCodeRead = result => {
if (result.data !== this.state.lastScannedUrl) {
LayoutAnimation.spring();
this.setState({ lastScannedUrl: result.data });
}
};
render() {
return (
<View style={styles.container}>
{this.state.hasCameraPermission === null
? <Text>Requesting for camera permission</Text>
: this.state.hasCameraPermission === false
? <Text style={{ color: '#fff' }}>
Camera permission is not granted
</Text>
: <BarCodeScanner
onBarCodeRead={this._handleBarCodeRead}
style={{
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
}}
/>}
{this._maybeRenderUrl()}
<StatusBar hidden />
</View>
);
}
_handlePressUrl = () => {
Alert.alert(
'Open this URL?',
this.state.lastScannedUrl,
[
{
text: 'Yes',
onPress: () => Linking.openURL(this.state.lastScannedUrl),
},
{ text: 'No', onPress: () => {} },
],
{ cancellable: false }
);
};
_handlePressCancel = () => {
this.setState({ lastScannedUrl: null });
};
_maybeRenderUrl = () => {
if (!this.state.lastScannedUrl) {
return;
}
return (
<View style={styles.bottomBar}>
<TouchableOpacity style={styles.url} onPress={this._handlePressUrl}>
<Text numberOfLines={1} style={styles.urlText}>
{this.state.lastScannedUrl}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.cancelButton}
onPress={this._handlePressCancel}>
<Text style={styles.cancelButtonText}>
Cancel
</Text>
</TouchableOpacity>
</View>
);
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#000',
},
bottomBar: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'rgba(0,0,0,0.5)',
padding: 15,
flexDirection: 'row',
},
url: {
flex: 1,
},
urlText: {
color: '#fff',
fontSize: 20,
},
cancelButton: {
marginLeft: 10,
alignItems: 'center',
justifyContent: 'center',
},
cancelButtonText: {
color: 'rgba(255,255,255,0.8)',
fontSize: 18,
},
});
It would be very nice if someone suggests me to solve this or give me an example(such as downgrading the expo version) so that I can implement this.
You can use
expo-barcode-scanner
Run expo install expo-barcode-scanner
Usage
You must request permission to access the user's camera before attempting to get it. To do this, you will want to use the Permissions API. You can see this in practice in the following example.
import * as React from 'react';
import {
Text,
View,
StyleSheet,
Button
} from 'react-native';
import Constants from 'expo-constants';
import * as Permissions from 'expo-permissions';
import {
BarCodeScanner
} from 'expo-barcode-scanner';
export default class BarcodeScannerExample extends React.Component {
state = {
hasCameraPermission: null,
scanned: false,
};
async componentDidMount() {
this.getPermissionsAsync();
}
getPermissionsAsync = async() => {
const {
status
} = await Permissions.askAsync(Permissions.CAMERA);
this.setState({
hasCameraPermission: status === 'granted'
});
};
render() {
const {
hasCameraPermission,
scanned
} = this.state;
if (hasCameraPermission === null) {
return <Text > Requesting
for camera permission < /Text>;
}
if (hasCameraPermission === false) {
return <Text > No access to camera < /Text>;
}
return ( <
View style = {
{
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-end',
}
} >
<
BarCodeScanner onBarCodeScanned = {
scanned ? undefined : this.handleBarCodeScanned
}
style = {
StyleSheet.absoluteFillObject
}
/>
{
scanned && ( <
Button title = {
'Tap to Scan Again'
}
onPress = {
() => this.setState({
scanned: false
})
}
/>
)
} <
/View>
);
}
handleBarCodeScanned = ({
type,
data
}) => {
this.setState({
scanned: true
});
alert(`Bar code with type ${type} and data ${data} has been scanned!`);
};
}
Note: Passing undefined to the onBarCodeScanned prop will result in no scanning. This can be used to effectively "pause" the scanner so that it doesn't continually scan even after data has been retrieved.
Allow all the permisions which gets popped.
You're good to go!!
Hope this helps.

Redirecting user based on his authentication

In my react native application, I want to check if a user has already logged in before, then he must be redirected to 'Home' directly without asking him for credentials again. The 'Home' component consists of logout button in a sidebar.
My current code works fine for new user logging, but I am stuck on how to check if again the user open the application, his login token should persist and he must be redirected to 'Home' directly.
Here is my code:
import React, { Component } from 'react'
import { Text, View, Image, TextInput, TouchableOpacity, ScrollView, AsyncStorage, ToastAndroid } from 'react-native'
import axios from 'axios';
export default class Login extends Component {
constructor(){
super();
this.state = {
username: '',
password: '',
isLoggedIn: false,
loginChecked: false,
}
}
componentDidMount(){
this.getItem('userID');
}
//function to extract storage token. Any name can be given ot it.
async getItem(item){
console.log('method ran login screen');
console.log(this.state.isLoggedIn)
try{
const value = await AsyncStorage.getItem(item);
if(value !== null){
this.setState({
isLoggedIn: true,
loginChecked: true
})
}
else{
this.setState({
isLoggedIn: false,
loginChecked: true
})
}
}
catch(error){
console.log(error)
}
console.log(this.state.isLoggedIn)
}
//function to remove storage token
async removeItem(item){
try{
const value = await AsyncStorage.removeItem(item);
if(value == null){
this.setState({
isLoggedIn: false
})
}
}
catch(error){
//handle errors here
}
}
userLogin = () => {
if(this.state.username != '' && this.state.password != ''){
axios.post('http://bi.servassure.net/api/login', {
username: this.state.username,
password: this.state.password
})
.then(res => {
let userToken = res.data.token;
console.log(res.data);
if(res.data.success){
AsyncStorage.setItem('userID', userToken);
this.setState({
isLoggedIn: true
})
this.props.navigation.navigate('Home');
}
else{
ToastAndroid.showWithGravity(
'Invalid login' ,
ToastAndroid.SHORT,
ToastAndroid.CENTER
);
}
})
.catch(err => {
console.log(err);
});
}
else{
ToastAndroid.showWithGravity(
'Please Enter Credentials' ,
ToastAndroid.SHORT,
ToastAndroid.CENTER
);
}
}
logOut(){
this.removeItem('userID');
}
render() {
return (
<ScrollView>
<View style={{justifyContent:'center', alignItems:'center'}}>
<View style={{marginVertical:20}}>
<Text>
Login to your account
</Text>
</View>
<View>
<TextInput
style={{width: 300, height: 50, borderColor: 'gray', borderWidth: 1, borderRadius: 10, marginVertical: 10}}
onChangeText={(username) => this.setState({username})}
placeholder='username'
autoCapitalize = 'none'
/>
<TextInput
style={{width: 300, height: 50, borderColor: 'gray', borderWidth: 1, borderRadius: 10}}
onChangeText={(password) => this.setState({password})}
placeholder='password'
secureTextEntry={true}
/>
</View>
<View style={{justifyContent: 'center', alignItems: 'center'}}>
<TouchableOpacity
style={{width: 300, height: 50, borderWidth:1, borderRadius: 50, borderColor: 'gray', justifyContent: 'center', alignItems: 'center', marginVertical: 10}}
onPress={this.userLogin}>
<Text>
LOGIN
</Text>
</TouchableOpacity>
<Text>Forget Password</Text>
</View>
</View>
</ScrollView>
)
}
}
Also, I have a SplashScreen before login:
import React, { Component } from 'react'
import { Text, View } from 'react-native'
export default class SplashScreen extends Component {
componentDidMount(){
setTimeout( () => {
this.props.navigation.navigate('Login')
}, 2000)
}
render() {
return (
<View style={styles.viewStyles}>
<Text style={styles.textStyles}> My App </Text>
</View>
)
}
}
const styles = {
viewStyles: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'orange'
},
textStyles: {
color: 'white',
fontSize: 40,
fontWeight: 'bold'
}
}
I am bit new to react native, please help to figure this out.
Do something like this in your Login.js file:
import {AsyncStorage} from react-native;
After getting the response success of login API you can do this:
AsyncStorage.setItem('userID', responsejson.user_detail.userID);
in the same way, you can store the token also
AsyncStorage.setItem('token', responsejson.user_detail.token);
Then in your splashscreen.js, import AsyncStorage the same way as above and then place this code in componentWillMount() or componentDidMount()
of your splashscreen.js
var value = AsyncStorage.getItem('token');
value.then((e)=>{
if (e == '' || e == null ){
this.props.navigation.replace('Login')
}else {
this.props.navigation.replace('Home')
}
})
Explanation: When splashscreen.js is loaded then it checks for the token in asyncstorage and if it gets the token navigate to Home screen else navigate to Login screen.
Import the React Navigation library and use the Switch Navigator. It was designed to handle app navigation based on the login status of the user.
This article explains everything with examples

How to store username after logout and show it in TextInput on next login?

I have a login screen where I will enter a username and then after login I will go to home screen.
Now what I want is once the user comes out of the app and then open it again then it has to show the the username that has entered before.
How can I do this? I am using react-native-router-flux for navigation.
Here is my code:
import React, { Component } from 'react';
import {
StyleSheet,
Text,
TextInput,
Button,
View,
AsyncStorage
} from 'react-native';
import { Actions } from 'react-native-router-flux';
export default class AsyncStorageExample extends Component {
constructor(props) {
super(props);
this.state = {
myKey: null
};
}
async getKey() {
try {
const value = await AsyncStorage.getItem('#MySuperStore:key')
if (this.state.myKey === value) {
Actions.dashboard();
}
this.setState({ myKey: value });
} catch (error) {
console.log('Error retrieving data' + error);
}
}
async saveKey(value) {
try {
await AsyncStorage.setItem('#MySuperStore:key', value);
} 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);
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to Demo AsyncStorage!
</Text>
<TextInput
style={styles.formInput}
placeholder="Enter key you want to save!"
value={this.state.myKey}
onChangeText={(value) => this.saveKey(value)}
/>
<Button
style={styles.formButton}
onPress={this.getKey.bind(this)}
title="Get Key"
color="#2196f3"
accessibilityLabel="Get Key"
/>
<Button
style={styles.formButton}
onPress={this.resetKey.bind(this)}
title="Reset"
color="#f44336"
accessibilityLabel="Reset"
/>
<Text style={styles.instructions}>
Stored key is = {this.state.myKey}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
padding: 30,
flex: 1,
alignItems: 'stretch',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
formInput: {
paddingLeft: 5,
height: 50,
borderWidth: 1,
borderColor: "#555555",
},
formButton: {
borderWidth: 1,
borderColor: "#555555",
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
marginTop: 5,
},
});
Using this I can get like this
When I enter some text then I will navigate to next screen; after that, if I come out of my app and open it again, then the previous value is not showing up in TextInput.
Where is it going wrong?
you can use AsyncStorage component of React Native. For more info AsyncStorage
You can set a value of user on logout.
AsyncStorage.setItem('UseName', 'name of user');
On login form get value from AsyncStorage in componentWillMount() method.
AsyncStorage.getItem('UserName')
.then((data) => {
if (data) {
this.setState({UserName:data}) //store data in state
}
}).done();

Slow state update in redux

So I have this problem where a variable update is slower than a route change.
When I have an error on for example my registration view, the error shows up instantly. When press back to come back to the login view, the error is being reset (action "clearErrors" is being fired on componentWillUnmount) to an empty string via an action. The problem is that I can se the error message on the login for a brief moment before it receives the new empty error state.
ErrorReducer.js
import {
ERROR,
CLR_ERROR
} from '../actions/types';
const INIT_STATE = {
error: ''
};
export default (state = INIT_STATE, action) => {
switch (action.type) {
case ERROR:
return { ...state, error: action.payload };
case CLR_ERROR:
return { ...state, error: '' };
default:
return state;
}
};
error.js (actions)
import { CLR_ERROR } from './types';
export const clearErrors = () => {
return (dispatch) => {
dispatch({ type: CLR_ERROR });
};
};
LoginForm.js
import React, { Component } from 'react';
import { View } from 'react-native';
import { Actions } from 'react-native-router-flux';
import { connect } from 'react-redux';
import { emailChanged, passwordChanged, loginUser, resetRoute, autoLogin } from '../actions';
import { Button, Input, Message } from './common';
class LoginForm extends Component {
componentWillUnmount() {
this.props.resetRoute();
}
onEmailChange(text) {
this.props.emailChanged(text);
}
onPasswordChange(text) {
this.props.passwordChanged(text);
}
onButtonPress() {
this.props.loading = true;
const { email, password } = this.props;
this.props.loginUser({ email, password });
}
render() {
return (
<View
style={{
flex: 1,
marginLeft: 10,
marginRight: 10,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
}}
keyboardShouldPersistTaps="always"
keyboardDismissMode="on-drag"
>
<Message
type="danger"
message={this.props.error}
/>
<Input
placeholder="din#email.se"
keyboardType="email-address"
returnKeyType="next"
onChangeText={this.onEmailChange.bind(this)}
value={this.props.email}
icon="ios-mail"
/>
<Input
secureTextEntry
placeholder="ditt lösenord"
onChangeText={this.onPasswordChange.bind(this)}
value={this.props.password}
icon="ios-key"
iconSize={22}
/>
<Button
loading={this.props.loading}
uppercase
color="primary"
label="Logga in"
onPress={this.onButtonPress.bind(this)}
/>
<Button
fontColor="primary"
label="Registrera"
onPress={() => Actions.register()}
/>
<Button
fontColor="primary"
label="Glömt lösenord"
onPress={() => Actions.resetpw()}
/>
</View>
);
}
}
const mapStateToProps = ({ auth, errors }) => {
const { email, password, loading, token } = auth;
const { error } = errors;
return { email, password, error, loading, token };
};
export default connect(mapStateToProps, {
emailChanged, passwordChanged, loginUser, resetRoute, autoLogin
})(LoginForm);
Message.js (component to show error)
import React from 'react';
import { View, Text } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { colors } from '../style';
export const Message = ({ type, message }) => {
const style = {
view: {
alignSelf: 'stretch',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
padding: 20,
margin: 15,
backgroundColor: colors[type],
borderRadius: 3,
elevation: 5,
shadowRadius: 5,
shadowColor: colors.smoothBlack,
shadowOffset: { width: 2.5, height: 2.5 },
shadowOpacity: 0.5
},
text: {
color: colors.alternative,
fontSize: 12,
alignSelf: 'center',
flex: 1
},
icon: {
marginRight: 20,
marginLeft: 0,
marginTop: 2,
alignSelf: 'center'
}
};
const getIcon = (iconType) => {
switch (iconType) {
case 'info':
return 'ios-information-circle';
case 'success':
return 'ios-checkmark-circle';
case 'danger':
return 'ios-alert';
case 'warning':
return 'ios-warning';
default:
return;
}
};
if (message.length > 0) {
return (
<View style={style.view}>
{(type) ? <Icon name={getIcon(type)} size={20} style={style.icon} /> : null}
<Text style={style.text}>{message}</Text>
</View>
);
}
return <View />;
};
I am running on device OnePlus3 with all console.logs removed, production build.
From what I have read, this should be fast. Am I doing something wrong here?
It's impossible to say without looking at your rendering code, but it's likely that the slowness is not caused by the time it takes for redux to update the state, but for React to re-render the UI after the dispatch has completed - possibly because it's busy re-rendering other things while your navigator is transitioning.
To guarantee the ordering of actions with redux-thunk, you can return a Promise from your thunk action creator and wait to navigate back until the action has been dispatched:
export const clearErrors = () => {
return (dispatch) => {
return new Promise(dispatch({ type: CLR_ERROR }));
};
};
In your view then, you can do the back navigation action once the error has been cleared:
// assuming the action creator has been passed
// to the component as props
this.props.clearErrors().then(() => navigator.back());