React Native AsyncStorage stops working once app is offline - android

I have a relatively simple app (my first) that needs to display information that is retrieved from a GraphQL query and then stored in AsyncStorage. Everything works fine until you turnoff data/Wifi connections and relaunch the app - it will not load the same local data it did when networking is on. This is the same on a physical or emulated Android device.
There are no data calls except when the user initially sets their details. The app is built with version 2.7.1 of Expo & AWS Amplify. I have wasted several days with this final issue and gotten the same behaviour with Expo SecureStore & Amplify Cache and am loath to go down the route of learning and including Redux on such a simple app...
//import from react native not react
import { AsyncStorage } from 'react-native'
//calling a function as app loads
componentDidMount() {
this._loadInitialState();
}
//retrieving String from AsyncStorage
_loadInitialState = async () => {
try {
const policyNum = await AsyncStorage.getItem('policyNum')
//...
} catch {
//...
}
//setting state
if (policyNum != null && policyNum != undefined) {
this.setState({ policyNum: policyNum })
//...
}
//the original setting of the item
setPolicyDetails = async () => {
if (this.state.policyNum != null) {
const policyNumber = this.state.policyNum
this.state.policyNumSet = true
try {
await AsyncStorage.setItem('policyNum', policyNumber)
} catch (err) {
//...
}
}
}

You are using badly the fact of change the state.
Where you do this:
this.state.policyNumSet = true
You should change the state with the setState() function like this:
this.setState({ policyNumSet: true })

This was a conflict with an external API

Are you storing a string? asyncstorage only can store strings . try using JSON.stringify and JSON.parse
_loadInitialState = async () => {
try {
var policyNum = await AsyncStorage.getItem('policyNum')
policyNum = JSON.parse(policyNum) // converting to original
//...
} catch {
//...
}
//setting state
if (policyNum != null && policyNum != undefined) {
this.setState({ policyNum: policyNum })
//...
}
//the original setting of the item
setPolicyDetails = async () => {
if (this.state.policyNum != null) {
const policyNumber = this.state.policyNum
this.setState({ policyNumSet: true })
try {
var policyNumberString = JSON.stringify(policyNumber)
await AsyncStorage.setItem('policyNum', policyNumberString) //converting to string
} catch (err) {
//...
}
}
}

Related

Flutter BloC repeat an event again after dio request time out

I have a problem on my flutter app, when try to load a data from api using dio and this api is private so need to be connected to the same network, so to check everything is fine I tried to connect using mobile data that means dio connection won't success and return timeout, when I call that inside BLoC and use BloCBuilder to build UI depending on state bloc return loadingstate then return errorstate and try to do the event again and fail then repeat this over and over, I just want to avoid this and return error state only and stop listening on that event
void _loadAllSpecialities(
LoadAllSpecialities event, Emitter<DoctorsState> emit) async {
emit(
const DoctorsLoadingState(),
);
emit(const DoctorsLoadingState());
final result = await doctorService.getAllSpeciality(event.jwtToken);
print(result.toString());
//has no error and data loaded
if (result.item1 == null) {
final speicailities = result.item2;
emit(DoctorsSpecialitiesLoaded(specialities: speicailities));
} else {
//has error (error not null)
emit(DoctorErrorState(result.item1!));
}
}```
.
class DoctorService {
final List<DoctorSpeciality> specialities = [];
final options = Options(
responseType: ResponseType.json,
receiveTimeout: 2000,
sendTimeout: 2000,
);
final _dio = Dio();
Future<Tuple<String?, List<DoctorSpeciality>>> getAllSpeciality(
String jwtToken) async {
specialities.clear();
var tuple = Tuple<String?, List<DoctorSpeciality>>(null, []);
try {
final response = await _dio.get<List>(ApiVars.specialitiesEndPoint,
options:
options.copyWith(headers: {"Authorization": "Bearer $jwtToken"}));
if (response.statusCode == 200) {
//has no data
if (response.data == null) {
//set error 1
tuple.setNewValues('No data loaded', []);
//print it
log(tuple.item1 ?? '');
//return tuple with error and empty list
return tuple;
}
//has data then map it into list of specialities
response.data?.forEach((element) {
//convert json to speciality and add it to specialities list
specialities.add(DoctorSpeciality.fromJson(element));
});
//set error to null and list to specialites list
tuple.setNewValues(null, specialities);
return tuple;
} else {
//set error to error with the code and list to empty list
tuple.setNewValues('error occur with code ${response.statusCode}', []);
log(tuple.item1 ?? '');
return tuple;
}
} on DioError catch (error) {
//set error to error message and list to empty list
tuple.setNewValues("doc service ${error.message}", []);
log(tuple.item1 ?? '');
return tuple;
}
}
}
I tried add droppable, sequential and didn't work
on<LoadAllSpecialities>(_loadAllSpecialities, transformer: droppable());
I solved the problem by adding Future before function that called inside the handler function and await it to end as code in below
///constructor called super and pass initial state...
on<DoctorsEvent>(
(event, emit) async {
try {
if (event is LoadAllSpecialities) {
// * load all specialities of doctors from api ...
//add await here
await _loadAllSpecialities(event, emit);
}
} catch (error) {
emit(DoctorErrorState(error.toString()));
}
},
);
}
//add future here
Future<void> _loadAllSpecialities(
LoadAllSpecialities event, Emitter<DoctorsState> emit) async {
emit(
const DoctorsLoadingState(),
);
emit(const DoctorsLoadingState());
final result = await doctorService.getAllSpeciality(event.jwtToken);
//has no error and data loaded
if (result.item1 == null) {
final speicailities = result.item2;
emit(DoctorsSpecialitiesLoaded(specialities: speicailities));
} else {
//has error (error not null)
emit(DoctorErrorState(result.item1!));
}
}

Flutter: type 'Future<bool?>' is not a subtype of type 'FutureOr<bool>' in type cast

I'm new on the Flutter & working on the integration of POS printing machine in flutter & using the pos_printer_manager package.
It shows an error in the catch part of this package i.e.
type 'Future<bool?>' is not a subtype of type 'FutureOr<bool>' in type cast
& pointing out in this code
/// [writeBytes] let you write raw list int data into socket
#override
Future<ConnectionResponse> writeBytes(List<int> data,
{bool isDisconnect: true}) async {
try {
if (!isConnected) {
await connect();
}
if (Platform.isAndroid || Platform.isIOS) {
if ((await (bluetooth.isConnected as FutureOr<bool>))) {
Uint8List message = Uint8List.fromList(data);
PosPrinterManager.logger.warning("message.length ${message.length}");
await bluetooth.writeBytes(message);
if (isDisconnect) {
await disconnect();
}
return ConnectionResponse.success;
}
return ConnectionResponse.printerNotConnected;
}
// else if (Platform.isIOS) {
// // var services = (await fbdevice.discoverServices());
// // var service = services.firstWhere((e) => e.isPrimary);
// // var charactor =
// // service.characteristics.firstWhere((e) => e.properties.write);
// // await charactor?.write(data, withoutResponse: true);
// return ConnectionResponse.success;
// }
return ConnectionResponse.unsupport;
} catch (e) {
print("Error : $e");
return ConnectionResponse.unknown;
}
}
This is due to bluetooth.isConnected as FutureOr<bool>.
So any big difference between Future<bool?> & FutureOr<bool> ?
Basically I faced type casting error in the package & I need a solution to handle this on the package side & how to manage the optional.
Based on your findings typecast is not required, it requires a null check
change this it to
if (Platform.isAndroid || Platform.isIOS) {
bool? isConnected = await bluetooth.isConnected;
if (isConnected != null && isConnected!) {
Uint8List message = Uint8List.fromList(data);
PosPrinterManager.logger.warning("message.length ${message.length}");
await bluetooth.writeBytes(message);
if (isDisconnect) {
await disconnect();
}
return ConnectionResponse.success;
}
return ConnectionResponse.printerNotConnected;
}
Resolved it by a simple check:
bool? btConnected = await bluetooth.isConnected ?? false;

firestore update function is not working properly

in my react native app im trying to get user position when app opened only once
heres my code below.
async function GetUserDoc() {
let userData = await userDataRef.get().catch(error => Alert.alert("getuser" + error.message))
const uid = userData.docs.map(x => x.id)
if (uid.length > 0) {
PosRefresher(uid[0])
}
}
async function PosRefresher(uid) {
if (uid.length > 0) {
let loc = await Location.getCurrentPositionAsync();
const ref = firestore().collection('users').doc(uid)
ref.get().then(doc => {
if (doc.exists) {
if (loc.coords.latitude !== 0 && loc.coords.longitude !== 0) {
console.log("posupdate")
ref.update({
lastKnownPosition: new firestore.GeoPoint(loc.coords.latitude, loc.coords.longitude)
})
}
}
}).catch(err => console.log("setposupdate err", err))
}
}
when i check console log i can see "posupdate" so its seems like working. but when i check firestore user location not updates.
if im refresh app from metro its updating
but if i close app totally and reopen its not updating. what am i missing?
thanks

React PWA detect new content on iOS is not working as expected

I use CRA PWA and add toast that's show when onupdatefound and onstatechange. it's working well in android and pc but in iOS it's not shown and content not refresh till close tab and open it again.
I searching long time and not found any good answer for this issue.
I have ServiceWorkerWrapper.ts
import React, { FC, useEffect } from 'react';
import { Snackbar, Button } from '#material-ui/core';
import * as serviceWorker from '../serviceWorkerRegistration';
const ServiceWorkerWrapper: FC = () => {
const [showReload, setShowReload] = React.useState(false);
const [counter, setCounter] = React.useState(0);
React.useEffect(() => {
let timer:any;
if (counter >= 0 && showReload) {
setTimeout(() => setCounter(counter - 1), 1000)
} else if (showReload) {
reloadPage();
}
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [counter]);
const onSWUpdate = (registration: ServiceWorkerRegistration) => {
if (registration && registration.waiting) {
setShowReload(true);
setCounter(2)
} else {
setShowReload(false);
}
};
useEffect(() => {
serviceWorker.register({ onUpdate: onSWUpdate });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const reloadPage = () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.getRegistration()
.then((reg:any) => {
reg.waiting.postMessage({ type: 'SKIP_WAITING' });
window.location.reload();
})
.catch((err) => console.log('Could not get registration: ', err));
}
};
return (
<Snackbar
open={showReload}
message="A new version is available!"
onClick={reloadPage}
ContentProps={{
className: "reload-snackbar"
}}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
action={
<Button
color="inherit"
size="small"
onClick={reloadPage}
>
Reload{showReload ? ` (${counter + 1})`:''}
</Button>
}
/>
);
}
export default ServiceWorkerWrapper;
serviceWorkerRegistration.ts
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://cra.link/PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);
type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};
export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://cra.link/PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl: string, config?: Config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
if (navigator.vendor === 'Apple Computer, Inc.') {
console.log('Safari!!!!');
if (registration.waiting) {
if (config && config.onUpdate) {
config.onUpdate(registration);
}
}
}
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl: string, config?: Config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log('No internet connection found. App is running in offline mode.');
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
})
.catch((error) => {
console.error(error.message);
});
}
}
service-worker.ts
/// <reference lib="webworker" />
/* eslint-disable no-restricted-globals */
// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
declare const self: ServiceWorkerGlobalScope;
clientsClaim();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }: { request: Request; url: URL }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
}
// If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
}
// If this looks like a URL for a resource, because it contains
// a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
}
// Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'),
// Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
// Any other custom service worker logic can go here.

How to know when the AsyncStorage in React-Native is Full?

I want to know when AsyncStorage is full in react native.
What do Error value we get when the AsyncStorage is full to react native or will something else happen?
We can get a value from AsyncStorage using the below code
try {
const value = await AsyncStorage.getItem('TASKS');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
if someone can suggest me a check in the above code to know when AsyncStorage is full. It would be really helpful.
Do the steps
import {AsyncStorage} from 'react-native';
AsyncStorage.setItem('Islogin', 'Yes');
And check that you have stored or not.
_storeData = async () => {
try {
let value = await AsyncStorage.getItem('Islogin');
if (value) {
if (value == 'Yes'){
console.log("You are auto login");
}else{
console.log("abc");
}
}else{
console.log("abc");
}
} catch (error) {
console.log("error" + error);
}
}

Categories

Resources