Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AsyncStorage.getItem() doesn't seem to work #18372

Closed
mrded opened this issue Mar 14, 2018 · 108 comments
Closed

AsyncStorage.getItem() doesn't seem to work #18372

mrded opened this issue Mar 14, 2018 · 108 comments
Labels
Bug Issue: Author Provided Repro This issue can be reproduced in Snack or an attached project. Ran Commands One of our bots successfully processed a command. Resolution: Locked This issue was locked by the bot.

Comments

@mrded
Copy link

mrded commented Mar 14, 2018

When I try to set a value via AsyncStorage.getItem(), I cannot request it back.

Environment

Environment:
OS: macOS High Sierra 10.13.3
Node: 9.8.0
Yarn: 1.5.1
npm: 5.6.0
Watchman: 4.9.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: Not Found

Packages: (wanted => installed)
react: ^16.3.0-alpha.1 => 16.3.0-alpha.1
react-native: 0.54.0 => 0.54.0

Expected Behavior

await AsyncStorage.setItem('foo', 'bar');
await AsyncStorage.getItem('foo').then(console.log); // 'bar'
await AsyncStorage.getAllKeys().then(console.log); // ['foo']

Actual Behavior

await AsyncStorage.setItem('foo', 'bar');
await AsyncStorage.getItem('foo').then(console.log); // null
await AsyncStorage.getAllKeys().then(console.log); // []

Steps to Reproduce

import { AsyncStorage } from 'react-native';

it('should be able to request a value after it was set', async () => {
  await AsyncStorage.setItem('foo', 'bar');
  const output = await AsyncStorage.getItem('foo');

  expect(output).toBe('bar');
});

it('should be able to see a new key after a value was set', async () => {
  await AsyncStorage.setItem('foo', 'bar');
  const output = await AsyncStorage.getAllKeys();

  expect(output).toContain('foo');
});
@react-native-bot
Copy link
Collaborator

Thanks for posting this! It looks like your issue may refer to an older version of React Native. Can you reproduce the issue on the latest stable release?

Thank you for your contributions.

How to ContributeWhat to Expect from Maintainers

@react-native-bot react-native-bot added Old Version ⏪ Ran Commands One of our bots successfully processed a command. labels Mar 14, 2018
@mrded
Copy link
Author

mrded commented Mar 14, 2018

Updated react-native => 0.54.0

@hramos hramos added Issue: Author Provided Repro This issue can be reproduced in Snack or an attached project. and removed Old Version ⏪ labels Mar 14, 2018
@hjJunior
Copy link

hjJunior commented Mar 15, 2018

I'm getting the same issue, and I'm using 0.54.0 react-native version, so what I can do to solve this? is It the stable version ?

Actual Behavior

await AsyncStorage.setItem('foo', 'bar'); 
await AsyncStorage.getItem('foo').then(console.log); // nothing happens
await AsyncStorage.getAllKeys().then(console.log); // nothing happens

Environment

react: 16.3.0-alpha.1
react-native: 0.54.0
npm: 5.7.1
yarn: 1.3.2
windows: 10
emulator: Nexus 5 API P

@xiaonull
Copy link

Try to run the install command again, it may to work.

@hjJunior
Copy link

@xiaonull did you mean I run npm install before run react-native run-android
If is it, I have tried, even I tried to unistall and after install aplication on the device

@react-native-bot react-native-bot added the Platform: macOS Building on macOS. label Mar 20, 2018
@arjasco
Copy link

arjasco commented Mar 22, 2018

Having the same issue with 0.52.0. Really frustrating.

If you call setItem and then immediately call getItem or getAllKeys to reveal all in the store it works as normal and the value will be present. Reload of the app and back to square one, getItem returns null.

@Metroninja
Copy link

Metroninja commented Mar 22, 2018

Running into this issue sporadically on 0.54.2 on Android.

@ohasy
Copy link

ohasy commented Mar 23, 2018

It is really frustrating. after few time of running the app. Aysnc AsyncStorage.getItem() stops working.
I tried many hacky way to work around it. but after few times. its just don't work.

@arjasco
Copy link

arjasco commented Mar 23, 2018

RN is pretty new to me, anyone know any of the maintainers on here we can ping to have a look?

The implementation is definitely not stable, there is another issue here: #12830

Don't really fancy using SQLite just to store a couple of integer values 😕

@ohasy
Copy link

ohasy commented Mar 23, 2018

I am thinking to use this as alternative : https://github.com/oblador/react-native-keychain
Edit: I was already using react-native-fs for my project. so, I used it to store a file containing JSON data, and fetched back on program starts. I know its not the right way. but its working perfectly, and I am really scared of using AsyncStorage now.

@AleskiWeb
Copy link

Just to add to this, I've noticed that if I am using AsyncStorage.getItem() and I make a change in a file, to trigger a live reload of the application in the emulator, but then at the same time its recompiling the JS, I then save once again, to interupt and trigger a new compilation, then it stops working and requires me to restart the application (react-native run-android again)

@lenoxzzedwin
Copy link

@AleskiWeb that is very stressful.
It's happening to me.

Some alternative?

@almorak
Copy link

almorak commented Jun 17, 2018

same here ...
let result = await AsyncStorage.getItem(key)
android just stuck there , try catch not work, only restart the app again or setting a timeout,
but it is not a solution. It still cannot load the data saved.

@nahidmbstu
Copy link

let value = await AsyncStorage.getItem("user");
this line blocks the execution ....
the next line is not working .....
i am using .......... "react-native": "0.55.3" and android one device....
its frustating........

@hosseinalipour
Copy link

the same issue, is it supposed to work with expo app or the issue is global?

@ImadeLake
Copy link

Hello
the same here.....

"dependencies": {
"expo": "^27.0.1",
"react": "16.3.1",
"react-native": "~0.55.2",
"react-native-router-flux": "^4.0.0-beta.31"
}

I don't understand why it's not working...

@mgambati
Copy link

It's 2 years bug, same with hot reload bug. These bugs are so old that they are mascots for the RN.
Now I understand why Airbnb is dropping RN.

@Jalalx
Copy link

Jalalx commented Jul 2, 2018

Any update on this?

@C0dekid
Copy link

C0dekid commented Jul 5, 2018

Same issue, still waiting for a fix!

@Sukumar-Abhijeet
Copy link

I also encountered the same issue. I was binding an async function in the UI of one screen. So whenever I was navigating to that screen, the app was getting stuck and restarting the app was not working. It was working only if i restart the expo app and then the project app.

Please check whether an async function is getting invoked on render or not. That could be the issue of AsyncStorage not fetching any item because the previous async has not completed yet. Thanks.

@skout90
Copy link

skout90 commented Jan 4, 2019

same issue......
in rn 0.57.8

@jclwong
Copy link

jclwong commented Jan 8, 2019

This resolved the issue for me. On a related thread: #14101 (comment)

After further investigation: in my case I had an AsyncTask in some Java code (a local web server in my case) that was blocking and hence blocking other AsyncTasks (which AsyncStorage relies on). Setting my AsyncTask to execute in parallel to other tasks (via myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) instead of myTask.execute()) fixed the issue.

My native Android code had reference to an AsyncTask, which for some reason mucks with AsyncStorage. Once removed it works as intended.

@Bradzer
Copy link

Bradzer commented Jan 20, 2019

Same issue for me.
It is such a shame that a such critical and old issue is not being solved.

@robertpitt
Copy link

Experiencing the same issue, AsyncStorage is just unusable.

@Bradzer
Copy link

Bradzer commented Feb 8, 2019

@hramos why is the bug report label removed when the issue is not resolved :(
It's a really critical issue that needs more attention than it has been given so far

@ohasy
Copy link

ohasy commented Feb 9, 2019 via email

@Georgge
Copy link

Georgge commented Feb 11, 2019

Problem is not getItem, the problem is setItem or that I think.
The difference between getItem and setItem is that set not return something (except a null). So, the await of setItem never pass to the next set. Actually, even never set the data.

So, the solution (at least for me) is: not to use await in setItem.

@eightyfive
Copy link

At last some valuable information! Thanks @Georgge

@AleksandarSavic95
Copy link

AleksandarSavic95 commented Feb 11, 2019

This is still an issue, and the problem is not in using await with setItem. iOS simulator (iPhone X) works perfectly, but on a real iPhone 6 and 8, it fails (storage is empty after going to another screen or reloading). Works well on OnePlus (Android).

@cpojer
Copy link
Contributor

cpojer commented Feb 15, 2019

This issue has been moved to react-native-async-storage/async-storage#12.

@chenop
Copy link

chenop commented Mar 3, 2019

To fix the live reload - switching to async await worked for me.

Checked this SO Answer (and vote up :-) )

@omurilo
Copy link

omurilo commented Apr 8, 2019

Have you remembered to put the item in asyncstorage as string (JSON.stringify) and when reading the parse item (JSON.parse) ?? this may be the mistake of many.

@jeffelector
Copy link

Problem is not getItem, the problem is setItem or that I think.
The difference between getItem and setItem is that set not return something (except a null). So, the await of setItem never pass to the next set. Actually, even never set the data.

So, the solution (at least for me) is: not to use await in setItem.

great !!! you save my day

@jorodriguez
Copy link

jorodriguez commented Jul 24, 2019

//Login.js
..
onClickListener = (viewId) => {
AsyncStorage.setItem('logeado', JSON.stringify(this.usuario.auth));
AsyncStorage.setItem('usuario', JSON.stringify(this.usuario));
that.props.navigation.navigate('Principal', { });
}

..

//Welcome.js

...
constructor(props) {
super(props);

this.state = {
  loading: false,
   usuarioSesion : null
}
this._bootstrapAsync();

}

_bootstrapAsync = async () => {
const usuario = await AsyncStorage.getItem('usuario');
Alert.alert("json",JSON.parse(usuario));
this.setState({usuarioSesion :usuario});
};

salir = () => {
AsyncStorage.removeItem('logeado');
AsyncStorage.removeItem('usuario');
this.props.navigation.navigate('AuthLoading', {});
}

its works for me.

@paddy57
Copy link

paddy57 commented Jul 29, 2019

I don't know what will be solution in your case but this one worked for me

Firstely i was importing some componets from react-native like this
import { Text, StyleSheet, TouchableHighlight, TextInput, } from 'react-native';
import { AsyncStorage } from 'react-native';

and the AsyncStorage.getItem or AsyncStorage.setItem was not working, whatever code was there after AsunStorage was not running, so

I Modified my import like to this
import { Text, StyleSheet, TouchableHighlight, TextInput, AsyncStorage } from 'react-native';

and now everything was working fine.
I don't know how it got resolved, but my AsyncStorage.setItem and AsyncStorage.getItem both was working fine

AsyncStorage.setItem('DEMO', 'false');

try {
let data = await AsyncStorage.getItem("DEMO");
alert(data);
}
catch (error) {

    }

@kamirt
Copy link

kamirt commented Aug 19, 2019

Hi everyone,

Problem is not getItem, the problem is setItem or that I think.
The difference between getItem and setItem is that set not return something (except a null). So, the await of setItem never pass to the next set. Actually, even never set the data.

So, the solution (at least for me) is: not to use await in setItem.

Not just this I think. I've used your solution, but getItem('key', callback) and getItem('key').then() also doesn't work. Also it does'nt work directly inside componentDidMount hook. It become working when I've took this away to another function like this:
_getItem = async function () {
const result = await AsyncStorage.getItem('key')
return result
}

componentDidMount () {
this._getItem().then((result) => {
..so something with result..
})
}`

@dmcfadden1
Copy link

AsyncStorage.getItem(key)
.then((value) => {
return value;
})

@b3hz4d
Copy link

b3hz4d commented Sep 19, 2019

I found solution for this
Use this link https://github.com/react-native-community/async-storage/blob/LEGACY/docs/advanced/DedicatedExecutor.md

@irishabhyadav90
Copy link

Even the custom Hooks (UseStorage) in React Native causing the same Problem.

import {useState, useEffect} from 'react';
import {AsyncStorage} from '@react-native-community/async-storage';

/* Hook for AsyncStorage */

const useStorage = (key, defaultValue) => {
const [storage, updateStorageValue] = useState(defaultValue, '');
async function getStorageValue() {
let value = key || defaultValue;

try {
  value = JSON.parse(await AsyncStorage.getItem(key)) || defaultValue;
} catch (e) {
} finally {
  updateStorageValue(value);
}

}

async function updateStorage(newValue) {
try {
if (newValue === null) {
await AsyncStorage.removeItem(key);
} else {
const value = JSON.stringify(newValue);
await AsyncStorage.setItem(key, value);
}
} catch (e) {
} finally {
updateStorageValue(newValue);
}
}

useEffect(() => {
getStorageValue();
}, [getStorageValue]);

return [storage, updateStorage];
};

export default useStorage;

@facebook facebook locked as resolved and limited conversation to collaborators Feb 15, 2020
@react-native-bot react-native-bot added the Resolution: Locked This issue was locked by the bot. label Feb 15, 2020
emrekgn referenced this issue in udacity/reactnd-UdaciFitness-complete Oct 23, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug Issue: Author Provided Repro This issue can be reproduced in Snack or an attached project. Ran Commands One of our bots successfully processed a command. Resolution: Locked This issue was locked by the bot.
Projects
None yet
Development

No branches or pull requests