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

Comments

@mrded
Copy link

@mrded 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

This comment has been minimized.

Copy link
Collaborator

@react-native-bot react-native-bot commented Mar 14, 2018

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

@mrded

This comment has been minimized.

Copy link
Author

@mrded mrded commented Mar 14, 2018

Updated react-native => 0.54.0

@hjJunior

This comment has been minimized.

Copy link

@hjJunior 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

This comment has been minimized.

Copy link

@xiaonull xiaonull commented Mar 18, 2018

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

@hjJunior

This comment has been minimized.

Copy link

@hjJunior hjJunior commented Mar 18, 2018

@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

@arjasco

This comment has been minimized.

Copy link

@arjasco 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

This comment has been minimized.

Copy link

@Metroninja Metroninja commented Mar 22, 2018

Running into this issue sporadically on 0.54.2 on Android.

@yasoza

This comment has been minimized.

Copy link

@yasoza yasoza 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

This comment has been minimized.

Copy link

@arjasco 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 😕

@yasoza

This comment has been minimized.

Copy link

@yasoza yasoza 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

This comment has been minimized.

Copy link

@AleskiWeb AleskiWeb commented Apr 12, 2018

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

This comment has been minimized.

Copy link

@lenoxzzedwin lenoxzzedwin commented Jun 15, 2018

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

Some alternative?

@almorak

This comment has been minimized.

Copy link

@almorak 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

This comment has been minimized.

Copy link

@nahidmbstu nahidmbstu commented Jun 17, 2018

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

This comment has been minimized.

Copy link

@HosseinAlipour HosseinAlipour commented Jun 23, 2018

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

@ImadeLak

This comment has been minimized.

Copy link

@ImadeLak ImadeLak commented Jun 24, 2018

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

This comment has been minimized.

Copy link

@mgambati mgambati commented Jun 29, 2018

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

This comment has been minimized.

Copy link

@Jalalx Jalalx commented Jul 2, 2018

Any update on this?

@C0dekid

This comment has been minimized.

Copy link

@C0dekid C0dekid commented Jul 5, 2018

Same issue, still waiting for a fix!

@programmerElephant

This comment has been minimized.

Copy link

@programmerElephant programmerElephant commented Dec 3, 2018

i am using AsyncStorage with mobx,but it doesn't work when first launch.here is my code
my App.js

    "react-native": "0.57.4",
export default class App extends Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    AsyncStorage.getItem('isFirstOpen')
      .then((value) => {
        let jsonValue = JSON.parse((value));
        if (!jsonValue) {
          let colorMessage = {
            'main': {
              'bgcolor': 'white',
              'recordButtonBg': '#8cc152'
            },
            'leftMain': {
              'bgcolor': 'white',
              'thumeTitle': 'jiben',
              'defaluLanguage': 'xitongyuyan',
              'switchState': false
            },
            'sFont': 'norml'
          }

// when my app first installed,init this config
          AsyncStorage.multiSet(
            [
              ['isFirstOpen', JSON.stringify('yes')],
              ['colorMessage', JSON.stringify(colorMessage)],
              ['languageInfo', JSON.stringify(DeviceInfo.getDeviceLocale())]
            ],
            (error, result) => {
              if (!error) {
                    console.log('already saved')
              }
            });
        } else {
        }
      })
  }
  render() {
    return (
      <Provider rootStore={stores}>
        <RootStack />
      </Provider>
    );
  }
}

my mobx rootStores

class RootStore {

    constructor() {
        this.ageStore = new AgeStore();
        this.colorStore = new BgColor();
    }
}

class BgColor {

    constructor() {
        AsyncStorage.getItem('colorMessage').then(action((data) => {
            this.color = JSON.parse(data);
        }))
    }

    @observable color = ''
    @computed get isHaveColor() {
        
        return this.color ? this.color : {
            'main': {
                'bgcolor': 'white',
                'recordButtonBg': '#8cc152'
            },
            'leftMain': {
                'bgcolor': 'white',
                'thumeTitle': 'jiben',
                'switchState': false,
                'defaluLanguage':'xitongyuyan'
            },
            'sFont': 'norml'
        };
    }
    @action
    setColor(newColor) {
        this.color = newColor;
    }
}

when i killed my app and launch again(or first launch my app),i can't get my 'colorMessage' from AsyncStorage in this place,any problem with my code?
Thanks.

@ditorahard

This comment has been minimized.

Copy link

@ditorahard ditorahard commented Dec 7, 2018

I'm also facing the same issue. Is there any update on this or maybe a workaround (other than using expo version) ? Thanks

@Sukumar-Abhijeet

This comment has been minimized.

Copy link

@Sukumar-Abhijeet Sukumar-Abhijeet commented Dec 14, 2018

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

This comment has been minimized.

Copy link

@skout90 skout90 commented Jan 4, 2019

same issue......
in rn 0.57.8

@jclwong

This comment has been minimized.

Copy link

@jclwong 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

This comment has been minimized.

Copy link

@Bradzer 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

This comment has been minimized.

Copy link

@robertpitt robertpitt commented Feb 8, 2019

Experiencing the same issue, AsyncStorage is just unusable.

@Bradzer

This comment has been minimized.

Copy link

@Bradzer 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

@yasoza

This comment has been minimized.

Copy link

@yasoza yasoza commented Feb 9, 2019

@Georgge

This comment has been minimized.

Copy link

@Georgge 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

This comment has been minimized.

Copy link

@eightyfive eightyfive commented Feb 11, 2019

At last some valuable information! Thanks @Georgge

@AleksandarSavic95

This comment has been minimized.

Copy link

@AleksandarSavic95 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

This comment has been minimized.

Copy link
Contributor

@cpojer cpojer commented Feb 15, 2019

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

@chenop

This comment has been minimized.

Copy link

@chenop chenop commented Mar 3, 2019

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

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

@murilokaos

This comment has been minimized.

Copy link

@murilokaos murilokaos 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.

@react-native-bot react-native-bot added the Bug label May 4, 2019
@jeffelector

This comment has been minimized.

Copy link

@jeffelector jeffelector commented Jun 30, 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.

great !!! you save my day

@jorodriguez

This comment has been minimized.

Copy link

@jorodriguez 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

This comment has been minimized.

Copy link

@paddy57 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

This comment has been minimized.

Copy link

@kamirt 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

This comment has been minimized.

Copy link

@dmcfadden1 dmcfadden1 commented Aug 23, 2019

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

@b3hz4d

This comment has been minimized.

Copy link

@b3hz4d b3hz4d commented Sep 19, 2019

@irishabhyadav90

This comment has been minimized.

Copy link

@irishabhyadav90 irishabhyadav90 commented Dec 16, 2019

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
You can’t perform that action at this time.