React Native - Async storage information is extracted after componentWillMount() - asynchronous

I am storing if a checkbox is checked or not using AsyncStorage. When I reload the app, I see from logs that inside the asynchronous variable the correct information is stored. But, it is loaded after componentWillMount. Because of that, the checkbox does not appear checked, as it should be.
I think a good workaround will be to change the checkbox properties inside the asynchronous function. Do you think that would be a good solution? Do you have other suggestions for showing the correct checkbox value?
My code:
constructor(props) {
super(props)
this.state = {isChecked: false}
this.switchStatus = this.switchStatus.bind(this)
}
async getCache(key) {
try {
const status = await AsyncStorage.getItem(key);
if (status == null)
status = false
console.log("my async status is " + status)
return status
} catch(error) {
console.log("error", e)
}
}
componentWillMount(){
// key string depends on the object selected to be checked
const key = "status_" + this.props.data.id.toString()
this.getCache = this.getCache.bind(this)
this.setState({isChecked: (this.getCache(key) == 'true')})
console.log("my state is" + this.state.isChecked)
}
switchStatus () {
const newStatus = this.state.isChecked == false ? true : false
AsyncStorage.setItem("status_" + this.props.data.id.toString(), newStatus.toString());
console.log("hi my status is " + newStatus)
this.setState({isChecked: newStatus})
}
render({ data, onPress} = this.props) {
const {id, title, checked} = data
return (
<ListItem button onPress={onPress}>
<CheckBox
style={{padding: 1}}
onPress={(this.switchStatus}
checked={this.state.isChecked}
/>
<Body>
<Text>{title}</Text>
</Body>
<Right>
<Icon name="arrow-forward" />
</Right>
</ListItem>
)
}
There is no difference if I put everything in componentWillMount in the constructor.

Thank you for your answers. I am pretty sure await will work too, but I solved the problem before getting an answer. What I did was set the state to false in the beginning, and then update it in getCache. This way, it will always be set after getting the information from the local phone storage.
async getCache(key) {
try {
let status = await AsyncStorage.getItem(key);
if (status == null) {
status = false
}
this.setState({ isChecked: (status == 'true') })
} catch(e) {
console.log("error", e);
}
}

you make use of the async - await, but you are not waiting for your method in componentWillMount(). Try this:
componentWillMount(){
// key string depends on the object selected to be checked
const key = "status_" + this.props.data.id.toString()
this.getCache = await this.getCache.bind(this) // <-- Missed await
this.setState({isChecked: (this.getCache(key) == 'true')})
console.log("my state is" + this.state.isChecked)
}

The return value of an async function is a Promise object. So you have to use then to access the resolved value of getCache. Change your code to the following and it should work.
componentWillMount(){
// key string depends on the object selected to be checked
const key = "status_" + this.props.data.id.toString();
this.getCache(key).then(status => {
this.setState({ isChecked: status === true });
})
}

Related

Flutter code in widgetsBinding.instance.addPostFrameCallback getting called multiple times

I am building a sign in functionality using bloc pattern, if the entered credentials are invalid, bloc will return a authErrorState, so I will display a invalid credentials popup as soon as the bloc return a authError State
please check the code :
if (state is IsAuthLoadingState) {
return const LoadingSpinnerWidget();
} else if (state is IsAuthenticatedState) {
WidgetsBinding.instance.addPostFrameCallback((_) {
stopTimer();
BlocProvider.of<AuthBloc>(context).add(LoadAuthStatus());
Navigator.pop(context, true);
});
} else if (state is AuthErrorState) {
WidgetsBinding.instance.addPostFrameCallback((_) {
stopTimer();
showCustomPopUp(state.message);
});
}
Bloc code :
void _onLoginUser(LoginUser event, Emitter<AuthState> emit) async {
emit(IsAuthLoadingState());
final UserLoggedInResponse userDetails =
await authRepository.handleLoginUser(event.phoneNumber, event.otp);
if (userDetails.status == "success") {
for (var item in userDetails.wishlist) {
await _localRepo.addWishlistItem(item);
}
for (var item in userDetails.cart) {
await _localRepo.addCartItem(item);
}
for (var item in userDetails.recentSearches) {
await _localRepo.addRecentSearchTerm(item);
}
await _localRepo.addPurchasedItems(userDetails.purchasedItemIds);
await _localRepo.setIsAuthenticated(
userDetails.accessToken, userDetails.userId);
emit(IsAuthenticatedState());
} else {
emit(AuthErrorState(
message: userDetails.message, content: userDetails.content));
}
}
But, the invalid credentials popup written in authErrorState is getting called multiple times.
Any help is really appreciated. Thank you.
As I didn't found any alternative options, I someone tried to manage this for now like this,
I used a bool variable called isErrorShown, and it was set to false by default,
once the code in widgetsBinding is executed, it will set the isErrorShown to true, function is widgetsBinding checks the value of isErrorShown and executes only if it is false :
else if (state is AuthErrorState) {
print("error state");
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!isErrorShown) {
stopTimer();
if (state.message ==
"user does not exits, please create user") {
Navigator.pushReplacementNamed(context, '/create-user',
arguments: CreateUserPage(
showProfile: widget.showProfile,
phoneNumber: phoneNumberController.text,
otp: otpController.text,
));
// BlocProvider.of<AuthBloc>(context).add(LoadAuthStatus());
// Navigator.pushNamed(context, '/create-user');
} else {
showCustomPopUp(state.message);
}
isErrorShown = true;
}
});

firebase reset password controller

Yesterday my app was launched, Ionic v1, and a few users entered the wrong password and can't log into the app.
The app uses firebase authentication. I have a __refs file that points to the database and have tried numerous things trying to get the reset to work.
I've tried referencing $firebaseAuth, of course my __refs, $firebase then use $firebase.auth()...
I didn't write the authentication of this app so I'm not real sure how it works. I'm hoping that someone can help me.
My reset controller
angular.module('formulaWizard').controller('ResetPasswordCtrl',
function($scope, $ionicLoading, $firebaseAuth, __Refs) {
$scope.user = {
email: ''
};
$scope.errorMessage = null;
var fbAuth = $firebaseAuth(__Refs.rootRef);
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
fbAuth.sendPasswordResetEmail($scope.user.email)
.then(showConfirmation)
.catch(handleError);
};
function showConfirmation() {
$scope.emailSent = true;
$ionicLoading.hide();
}
function handleError(error) {
switch (error.code) {
case 'INVALID_EMAIL':
case 'INVALID_USER':
$scope.errorMessage = 'Invalid email';
break;
default:
$scope.errorMessage = 'Error: [' + error.code + ']';
}
$ionicLoading.hide();
}
});
My Refs file
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
customers: ref.child('customers'),
}
});
I can't take credit for the answer it was provide by Abimbola Idowu on HackHands.
Since I paid for the answer I thought I would share it with anyone else that might also be stumped by this.
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
__Refs.rootRef.resetPassword({ email: $scope.user.email }, function(error) {
if (error === null) {
showConfirmation();
} else {
handleError()
}
});
};
This is the __refs service
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
}
});

Make/ Create checkbox component in react native

I have been facing some issues with the native base checkbox and AsynStorage. In fact, AsynStorage only accepts strings by default BUT can store boolean variables also, I tried to use that method but I get a string stored every time.
While the checkbox does only accept boolean variables and throws a warning if I tried to use a string and it does not show the previous state of the checkbox (checked or not ).
So, I decided to make my own checkbox using TouchbleOpacity .. So do you guys have any idea how to make it ?
Here is the result i want to achieve:
So, the purpose is to make a checkbox settings page that controls the style of a text in another page and to get the checkbox as left the previous time, for an example : if I check it , I change the page and go back again to the settings page , I need to find it checked (indicating the previous state)
The code is
in the settings page :
toggleStatus() {
this.setState({
status: !this.state.status
});
AsyncStorage.setItem("myCheckbox",JSON.stringify(this.state.status));
}
// to get the previous status stored in the AsyncStorage
componentWillMount(){
AsyncStorage.getItem('myCheckbox').then((value) => {
this.setState({
status: value
});
if (this.state.status == "false") {
this.setState({
check: false
});
}
else if (this.state.status == "true") {
this.setState({
check: true
});
}
if (this.state.status == null) {
this.setState({
check: false
});
}
});
}
render {
return(
...
<CheckBox
onPress={() => { this.toggleStatus() }
checked={ this.state.check }/>
)}
In other page :
componentDidMount(){
AsyncStorage.getItem('myCheckbox').then((value) => {
JSON.parse(value)
this.setState({
status: value
});
});
}
This code change the status after TWO clicks and I don't know why and i get this weird output in the console, every time I click the checkbox
If you take a look at AsyncStorage documentation, you can see that, in fact, the method getItem() will always return a string (inside the promise).
For the problem with the AsyncStorage you should consider trying to parse this string returned to a boolean using this method explained here and then use this parsed value inside the native base checkbox.
But if you want to do your own component, try doing something like this:
export default class Checkbox extends Component {
constructor(){
super();
this.state = { checked: false }
}
render(){
return(
<TouchableOpacity
onPress={()=>{
this.setState({ checked : !this.state.checked });
}}
>
<Image source={this.state.checked ? require('checkedImagePath') : require('uncheckedImagePath')} />
</TouchableOpacity>
);
}
}
You will need to set some style to this image to configure it the way you want.
-- Based on your edition:
I can't see nothing wrong on your toggleStatus() method in settings page, but try changing your componentWillMount() to this:
componentWillMount(){
AsyncStorage.getItem('myCheckbox').then((value) => {
if (value != null){
this.setState({
check: (value == 'true')
});
}
});
}
However in the other page the line you do JSON.parse(value) is doing nothing, once you are not storing the result anywhere.

navigation after AsyncStorage.setItem: _this3.navigateTo is not a function

Currently, I am implementing a chat. After user pressed a chat button, the app will navigate the user to the Chat component. The chat content will simply store in firebase and chatId is needed to identify which chat belongs to the user.
Since I don't know how to pass props during navigation, I decided to save the CurrentChatId in AsyncStorage. After navigated to the Chat component, it will get the CurrentChatId from AsyncStorage so that I can map the chat content with the firebase.
However, I got the error _this3.navigateTo is not a function with code below:
let ref = FirebaseClient.database().ref('/Chat');
ref.orderByChild("chatId").equalTo(chatId).once("value", function(snapshot) {
chatId = taskId + "_" + user1Id + "_" + user2Id;
if (snapshot.val() == null) {
ref.push({
chatId: chatId,
taskId: taskId,
user1Id: user1Id,
user2Id: user2Id,
})
}
try {
AsyncStorage.setItem("CurrentChatId", chatId).then(res => {
this.navigateTo('chat');
});
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
}
The function navigateTo is copied from the demo app of NativeBase
import { actions } from 'react-native-navigation-redux-helpers';
import { closeDrawer } from './drawer';
const {
replaceAt,
popRoute,
pushRoute,
} = actions;
export default function navigateTo(route, homeRoute) {
return (dispatch, getState) => {
const navigation = getState().cardNavigation;
const currentRouteKey = navigation.routes[navigation.routes.length - 1].key;
dispatch(closeDrawer());
if (currentRouteKey !== homeRoute && route !== homeRoute) {
dispatch(replaceAt(currentRouteKey, { key: route, index: 1 }, navigation.key));
} else if (currentRouteKey !== homeRoute && route === homeRoute) {
dispatch(popRoute(navigation.key));
} else if (currentRouteKey === homeRoute && route !== homeRoute) {
dispatch(pushRoute({ key: route, index: 1 }, navigation.key));
}
};
}
You should bind this to the function that contains the try & catch. The best practice is to add this bind the constructor of the the component:
constructor(props) {
super(props);
this.myFunctoin = this.myfuction.bind(this);
}
Finally, I solved the problem. It is really because this.navigateTo('chat'); is inside function(snapshot)
ref.orderByChild("chatId").equalTo(chatId).once("value", function(snapshot) {
chatId = taskId + "_" + user1Id + "_" + user2Id;
if (snapshot.val() == null) {
ref.push({
chatId: chatId,
taskId: taskId,
user1Id: user1Id,
user2Id: user2Id,
})
}
}
try {
AsyncStorage.setItem("CurrentChatId", chatId).then(res => {
this.navigateTo('chat');
});
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
Take it out from the function will solve the problem.

Calling setState in render is not avoidable

React document states that the render function should be pure which mean it should not use this.setState in it .However, I believe when the state is depended on 'remote' i.e. result from ajax call.The only solution is setState() inside a render function
In my case.Our users can should be able to log in. After login, We also need check the user's access (ajax call )to decide how to display the page.The code is something like this
React.createClass({
render:function(){
if(this.state.user.login)
{
//do not call it twice
if(this.state.callAjax)
{
var self=this
$.ajax{
success:function(result)
{
if(result==a)
{self.setState({callAjax:false,hasAccess:a})}
if(result==b)
{self.setState({callAjax:false,hasAccess:b})}
}
}
}
if(this.state.hasAccess==a) return <Page />
else if(this.state.hasAccess==a) return <AnotherPage />
else return <LoadingPage />
}
else
{
return <div>
<button onClick:{
function(){this.setState({user.login:true})}
}>
LOGIN
</button>
</div>
}
}
})
The ajax call can not appear in componentDidMount because when user click LOGIN button the page is re-rendered and also need ajax call .So I suppose the only place to setState is inside the render function which breach the React principle
Any better solutions ? Thanks in advance
render should always remain pure. It's a very bad practice to do side-effecty things in there, and calling setState is a big red flag; in a simple example like this it can work out okay, but it's the road to highly unmaintainable components, plus it only works because the side effect is async.
Instead, think about the various states your component can be in — like you were modeling a state machine (which, it turns out, you are):
The initial state (user hasn't clicked button)
Pending authorization (user clicked login, but we don't know the result of the Ajax request yet)
User has access to something (we've got the result of the Ajax request)
Model this out with your component's state and you're good to go.
React.createClass({
getInitialState: function() {
return {
busy: false, // waiting for the ajax request
hasAccess: null, // what the user has access to
/**
* Our three states are modeled with this data:
*
* Pending: busy === true
* Has Access: hasAccess !== null
* Initial/Default: busy === false, hasAccess === null
*/
};
},
handleButtonClick: function() {
if (this.state.busy) return;
this.setState({ busy: true }); // we're waiting for ajax now
this._checkAuthorization();
},
_checkAuthorization: function() {
$.ajax({
// ...,
success: this._handleAjaxResult
});
},
_handleAjaxResult: function(result) {
if(result === a) {
this.setState({ hasAccess: a })
} else if(result ===b ) {
this.setState({ hasAccess: b })
}
},
render: function() {
// handle each of our possible states
if (this.state.busy) { // the pending state
return <LoadingPage />;
} else if (this.state.hasAccess) { // has access to something
return this._getPage(this.state.hasAccess);
} else {
return <button onClick={this.handleButtonClick}>LOGIN</button>;
}
},
_getPage: function(access) {
switch (access) {
case a:
return <Page />;
case b:
return <AnotherPage />;
default:
return <SomeDefaultPage />;
}
}
});

Resources