Can React Native AsyncStorage use to store data forever? - react-native

I want to store app data in AsyncStorage. And I want to persist that data and never get lost when app is going to refresh. Actually I'm going to create a job listing site and I want that user choose cities once whom jobs he wants to see and save that information forever.
I'm doing like this.
deviceStorageCity.saveItem("cities", checkedCities);
export const deviceStorageCity = {
async saveItem(key, value) {
try {
var jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(value));
return jsonOfItem;
} catch (error) {
console.log('AsyncStorage Error: ' + error.message);
}
}
};
But when I refresh state of that page is also refreshed.
Any help would be appriciated.

Related

In which file do I set a key in react native async storage for the first time the app starts?

I am developing a react native app and I would like data persistence. Async storage is working fine as I expect it to, however the problem is that I initialize a key 'servers' in a component and and call the setItem function in componentDidMount function. Now because of this every time I terminate the app and run it again all the data from the previous session is removed as the 'servers' key is reset when the component is mounted. I understand why this is causing the problem so I want to know where should I set the key in my code that it will not reset on every time my component mounts.
This is the function that I call in componentDidMount. This is the only way to declare a key in Async storage correct? because without it I would not be able to call getItem.
const save = async () => {
try {
server_list = await AsyncStorage.setItem('server_list', JSON.stringify({servers: []}));
}
catch (e){
console.log("Failed to load")
}
}
You can achieve this by filling the AsyncStorage only as long as there is no data under the server_list key.
This would look like this:
setServerList = async (value) => {
try {
const serverList = await AsyncStorage.getItem('server_list');
if(serverList === null) {
await AsyncStorage.setItem('server_list', value)
}
} catch(e) {
// save error
}
console.log('Done.')
}
You can still call this in the componentDidMount and your server list will no longer be overwritten

Can I use a function with async await inside ComponentDidMount in React Native?

I am using AsyncStorage.getItem in React Native.
As soon as the Application loads, I want to get the saved data in the device memory using AsyncStorage.getItem. I thought of using ComponentDidMount(). So as soon as the components are loaded, I want to run the AsyncStorage.getItem automatically and save the data to the array DATA. This way the user will not push any button to start rendering what is saved on the memory of the device.
I used the code below, but I do not see any console.log activity. But the console.log works on my other pages on same program here. It seems the ComponentDidMount() did not get executed.
Thanks!
componentDidMount(){
async () => {
try {
const HomeData = await AsyncStorage.getItem('#MyApp_Homekey')
return HomeData
} catch (e) {
console.log('There was error.')
}
if(!HomeData){
console.log('There are no Dimmer Light saved in the memory.')
}
else {
console.log('There is value in data after getItem.')
this.setState(DATA = HomeData)
}
}
As metioned in comment you should use async for componentDidMount as:-
componentDidMount = async () => {
const HomeData = await AsyncStorage.getItem('#MyApp_Homekey')
if(!HomeData){
console.log('There are no Dimmer Light saved in the memory.')
}
else {
console.log('There is value in data after getItem.')
this.setState(DATA = HomeData)
}
}

Data retrieve late from `asyncStorage` in react-native in drawer navigation

I have a user preferences screen in my app in which data is managed using asyncStorage. Whenever I change some value in preferences, I need to reflect that change in other screens of the app. But it does not show changes immediately but shows them when I reload the app. What should I do ..?
I am fetching data using: multiGet() in ComponentWillMount() and ComponentDidMount() and transitioning between screens with drawerNavigation.
I have even tried to use a global variable to reflect the changes but I does not help. Should I use redux? What should I do ? Thanks in advance.
use async-await to fetch data from asyncStorage
like this
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('TASKS');
if (value !== null) {
// update your ui
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};

Redux + Rest API + Realm JS in React Native

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?

The code below AsyncStorage does not run

I am working on my first React Native app. I am trying to learn how AsyncStorage works, but I somehow can't make it work even though it is said to be simple.
I am trying to save the data to storage, whenever the store is updated.
The problem is that the code below the line:
"await AsyncStorage.setItem("TODOS", jTodo)" does not seem to run. I don't know what the problem is...
const unsubscribe = store.subscribe(save);
async function save(){
try {
const todos = store.getState().todos
console.log(todos)
const jTodo = JSON.stringify(todos)
await AsyncStorage.setItem("TODOS", jTodo)
console.log("saving 2: " + todos);
} catch (e) {
console.error('Failed to save todos.' + todos)
}
}
The same is the case when I try to load data from storage. Again the code below the line: "const jTodos = await AsyncStorage.getItem('TODOS')" does not seem to run.
async function load() {
try {
console.log("so far even better")
const jTodos = await AsyncStorage.getItem('TODOS')
const todos = JSON.parse(jTodos);
console.log(todos);
todos.map((todo) => this.props.addTodo(todo))
} catch (e) {
console.error('Failed to load todos.')
}
}
load();
I hope some of you can point out what the problem is! Thank you in advance!!
If you are using android there is known issues with it not working.
"cold boot" your emulator from android studio.
https://github.com/facebook/react-native/issues/14101