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);
}
}
Related
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;
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
In my react native app, I ask for permission to access the camera roll as so:
getPermissionAsync = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status !== "granted") {
alert("Sorry, we need camera roll permissions to make this work!");
}
await this.setState({ permission: status === "granted" });
};
_pickMedia = async (index, type) => {
if (this.state.permission != true) {
await this.getPermissionAsync();
}
if (this.state.permission == true) {
// get image
} catch (E) {
console.log(E);
}
}
};
This works as expected during testing, but for my published version on Google Play, status is returned as undetermined whether or not the user gives permission. What does this mean?
Upgrading the react-native-community#react-native-permissions to 2.0.0 solves the issue.
Refer : https://github.com/react-native-community/react-native-permissions/issues/295
I got this problem when i expo publish my react native app with or without --release-channel dev flag.
I set up a config file environment.js to get different release version like this :
import Constants from "expo-constants";
import { Platform } from "react-native";
const localhost = Platform.OS === "ios" ? "localhost:8080" : "10.0.2.2:8080";
const ENV = {
localhost: {
//apiUrl: localhost,
apiUrl: "http:xxxx",
},
dev: {
apiUrl: "http:xxxx",
},
staging: {
apiUrl: "http:xxxx",
// Add other keys you want here
},
prod: {
apiUrl: "http:xxxx",
// Add other keys you want here
},
};
const getEnvVars = (env = Constants.manifest.releaseChannel) => {
// What is __DEV__ ?
// This variable is set to true when react-native is running in Dev mode.
// __DEV__ is true when run locally, but false when published.
if (__DEV__ || env === undefined || env === null || env === "") {
return ENV.localhost;
} else if (env.indexOf("dev") !== -1) {
return ENV.dev;
} else if (env.indexOf("staging") !== -1) {
return ENV.staging;
} else if (env.indexOf("prod") !== -1) {
return ENV.prod;
}
};
export default getEnvVars;
I intercept the config with creation of new intance of axios like this :
import axios from "axios";
import { getKey } from "./deviceStorage";
import getEnvVars from "../../environment";
const { apiUrl } = getEnvVars();
const instance = axios.create({
// .. where we make our configurations
baseURL: apiUrl,
});
instance.interceptors.request.use((config) => {
const token = getKey("id_token");
token.then((value) => {
config.headers.Authorization = value ? `Bearer ${value}` : "";
});
return config;
});
export default instance;
when i emulate on my device everything work fine but when i expo publish and scan QR code with my device the app crash after splash screen and i got this error say :
So if i understand well the Constants.manifest.releaseChannel is undefined, any idea why this happen ? do i miss somthing on the import ?
When i put the Api URL directly on my axios interceptors everything work fine.
import axios from "axios";
import { getKey } from "./deviceStorage";
//import getEnvVars from "../../environment";
//const { apiUrl } = getEnvVars();
const instance = axios.create({
// .. where we make our configurations
baseURL: "http://xxxx",
});
instance.interceptors.request.use((config) => {
const token = getKey("id_token");
token.then((value) => {
config.headers.Authorization = value ? `Bearer ${value}` : "";
});
return config;
});
export default instance;
export const ApiUrls = {
authPatient: "/xxx",
authPractician: "/xxx",
};
Thanks for help.
I find my problem here and maybe will help anyone on the future so :
i delete the env parameter on the getEnvVars and i declared inside the function and everything work fine :
const getEnvVars = () => {
const env = Constants.manifest.releaseChannel;
if (!__DEV__ && env) {
switch (env) {
case env.indexOf("dev") !== -1:
return ENV.dev;
case env.indexOf("staging") !== -1:
return ENV.staging;
case env.indexOf("prod") !== -1:
return ENV.prod;
default:
return ENV.localhost;
}
}
return ENV.localhost;
};
Moving the declaration of env into the function didn't work for me so I cut out the function altogether and that fixed my issue up. Going to have to figure out a way to rewrite it. But thank you for posting this anyways
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) {
//...
}
}
}