I'm building a React Native application that require to persist some values. But I don't want to trouble setting up backend and cloud databases for simple and small data. The dataset I want to persist is like 81 array items that has boolean values in each.
[true, true, false .... ]
OR
[{id: int, isCompleted: bool}, {id: int, isCompleted: bool},...]
Since I'm a React web developer and if it is a web application, I would be using local storage. But in React Native, what kind of storage that I can use that's local to the device only?
Maybe the best solution in your case is to use AsyncStorage library. Is simple to use and can be stored directly on the device.
import { AsyncStorage } from "react-native";
_store = async () => {
try {
await AsyncStorage.setItem('array', yourArray);
} catch (error) {
// Error
}
}
_rertrive = async () => {
try {
const value = await AsyncStorage.getItem('array');
if (value !== null) {
console.log(value);
}
} catch (error) {
// Error
}
}
Related
I am working on an app that records the location when the aplication is active or in the background.
After Permissions.getAsync got depricated, my app is not recording the coordonates when in background.
I understand I have to change to requestForegroundPermissionsAsync and requestBackgroundPermissionsAsync but I can not make it work.(I don't know how to use requestBackgroundPermissionsAsync)
Here is the code:
import { useState, useEffect } from 'react';
import {
Accuracy,
requestForegroundPermissionsAsync,
requestBackgroundPermissionsAsync,
watchPositionAsync
} from 'expo-location';
export default (shouldTrack, callback) => {
const [err, setErr] = useState(null);
useEffect(() => {
let subscriber;
const startWatching = async () => {
try {
const { granted } = await requestForegroundPermissionsAsync()
if (!granted) {
throw new Error('Location permission not granted');
}
subscriber = await watchPositionAsync(
{
accuracy: Accuracy.BestForNavigation,
timeInterval: 1000,
distanceInterval: 10
},
callback
);
} catch (e) {
setErr(e);
}
};
Question needs additional information to troubleshoot. For starters, are you on iOS\Android\both? Does it work on one platform but not the other? What permissions are listed in app.json (is this a managed\bare workflow)? Are the foreground updates working? Background updates require additional code and none of that is included here.
Have you gone through Expo's documentation? https://docs.expo.io/versions/latest/sdk/location
I am using MongoDB Realm Sync on my React Native app. When I start my app online and later disconnect internet, my realm works fine. I can see my data and also I can write data which syncs with server when I go back online. But when I start my app completely offline, my app does not show any data. From what I understand, realm is suppose to read local database and return data even when the app starts from complete offline. Isn't it ? How can I access my data when I start my app offline ? Below is my code I've used to sync with server.
const config = {
schema: [sessionSchema],
sync: {
user,
partitionValue: 'Test',
},
};
try {
Realm.open(config)
.then((openedRealm) => {
if (canceled) {
openedRealm.close();
return;
}
realmRef.current = openedRealm;
const syncSessions = openedRealm.objects('session');
openedRealm.addListener('change', () => {
setSessions([...syncSessions]);
});
setSessions([...syncSessions]);
}
} catch (e) {
console.log('ERROR', e);
}
const OpenRealmBehaviorConfiguration = {
type: "openImmediately",
}
const configuration = {
schema: [UserSchema],
sync: {
user: app.currentUser,
partitionValue: "user_1",
// Add this two lines below
newRealmFileBehavior: OpenRealmBehaviorConfiguration,
existingRealmFileBehavior: OpenRealmBehaviorConfiguration,
}
}
I found an answer for similar question here: https://developer.mongodb.com/community/forums/t/open-synced-local-database-when-completely-offline/11169/2
You can do something like:
async function getRealm() {
const app = new Realm.App("your-app-id");
if (app.currentUser) {
// A user had already logged in - open the Realm synchronously
return new Realm(getConfig(app.currentUser));
}
// We don't have a user - login a user and open the realm async
const user = await app.logIn(Realm.Credentials.anonymous());
return await Realm.open(getConfig(user));
}
function getConfig(user) {
return {
sync: {
user,
partitionValue: "my-partition"
}
};
}
I am using react native router flux in android project for routing when i jump from one component to another than the history of last component is remove from stack i want to store components history please anyone.
instead of jump you can use
Action.keynameofyournextpage()
ex to go to page1 to page2
can use
Actions.page2()
in page 1
If you want to save a record of the components, use the AsyncStorage module to save them.
Example
import {AsyncStorage} from 'react-native';
//set data
_storeData = async () => {
try {
await AsyncStorage.setItem('componenthistory', componenthistory);
} catch (error) {
// Error saving data
}
};
...
//get data
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('componenthistory');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};
I am developing an app that controls IOT devices via REST API.
I am using Realm database inside the app to keep historical data captured by IOT sensors. I also decided to use it to persist information about user and devices. redux-persist didn't seem like the best choice since the app will eventually deal with big tables of data of historical data.
I am now building my Redux actions with Redux-Thunk and I am in doubt about what would be the ideal workflow/data flow. I am currently calling realm inside redux actions like this:
function addNew(deviceIp) {
const request = () => { return { type: c.ADD_REQUEST } };
const success = (payload) => { return { type: c.ADD_SUCCESS, payload} };
const failure = (payload) => { return { type: c.ADD_FAILURE, payload } };
return async (dispatch,getState) => {
dispatch(request());
try {
const res = await apiService.getIt(deviceIp + urls.general);
// Convert responses to date before Realm Insertion
const newDevice = {
...res.deviceInfo[0],
host: deviceIp,
manufacturingDate: new Date(res.deviceInfo[0].manufacturingDate),
lastFwUpdateDate: new Date(res.deviceInfo[0].lastFwUpdateDate),
firstLaunchDate: new Date(res.deviceInfo[0].firstLaunchDate),
lastResetDate: new Date(res.deviceInfo[0].lastResetDate)
};
const addedDevice = await realmActions.createNew('Device',newDevice);
dispatch(success(addedDevice));
}
catch (error)
{
dispatch(failure(error));
}
};
}
realmActions.createNew(collectionName, newEntry) is a method I have created to add new entries to the specified collection in Realm DB. I have one main concern about this methodology.:
It seems to me a bit of an overkill to write objects to both Realm and Redux. But Realm will be useful to persist this data in case the user closes and re-opens the app. What do you think about the approach I am taking. Would you suggest anything cleaner or smarter?
I am using react-native 0.49.3 version, My Question is how to get the device token in react native for both IOS and Android I tried with this link but it not working for me, right now I tried in IOS. how to resolve it can one tell me how to configure?
I tried different solutions and I've decided to use React Native Firebase.
Here you will find everything about Notifications.
Also, you can use the others libraries that come with Firebase, like Analytics and Crash Reporting
After set up the library you can do something like:
// utils/firebase.js
import RNFirebase from 'react-native-firebase';
const configurationOptions = {
debug: true,
promptOnMissingPlayServices: true
}
const firebase = RNFirebase.initializeApp(configurationOptions)
export default firebase
// App.js
import React, { Component } from 'react';
import { Platform, View, AsyncStorage } from 'react-native';
// I am using Device info
import DeviceInfo from 'react-native-device-info';
import firebase from './utils/firebase';
class App extends Component {
componentDidMount = () => {
var language = DeviceInfo.getDeviceLocale();
firebase.messaging().getToken().then((token) => {
this._onChangeToken(token, language)
});
firebase.messaging().onTokenRefresh((token) => {
this._onChangeToken(token, language)
});
}
_onChangeToken = (token, language) => {
var data = {
'device_token': token,
'device_type': Platform.OS,
'device_language': language
};
this._loadDeviceInfo(data).done();
}
_loadDeviceInfo = async (deviceData) => {
// load the data in 'local storage'.
// this value will be used by login and register components.
var value = JSON.stringify(deviceData);
try {
await AsyncStorage.setItem(config.DEVICE_STORAGE_KEY, value);
} catch (error) {
console.log(error);
}
};
render() {
...
}
}
Then you can call the server with the token and all the info that you need.