简体   繁体   中英

React Native AsyncStorage Error when I want store data

I'm doing an operation inside my function and I want to store my JSON data with AsyncStorage and use it elsewhere, but I'm getting an error in react native

this is my code block;

                  onPress={() => {
                    press = item.id;
                    // console.warn(press);

                    ars = options;
                    dd = JSON.stringify(ars);
                    cc = JSON.parse(dd);
                    for (var i = 0; i < cc.length; i++) {
                      if (cc[i].id == press) {
                        // console.warn(cc[i]);
                        var productData = cc[i];

                        var stri = JSON.stringify(cc[i]);
                        AsyncStorage.setItem('ProductData', stri);
                        var abc = AsyncStorage.getItem('ProductData');
                        console.warn(stri);
                        console.warn(abc);
                      }
                    }
                  }}>

console.warn(stri) 输出是;console.warn(abc 输出为 ;)

how can i solve that problem?

thanks.

  var abc = await AsyncStorage.getItem('ProductData');

add await as it is promise that all

so whole code will look like this

                  onPress={async () => {
                press = item.id;
                // console.warn(press);

                ars = options;
                dd = JSON.stringify(ars);
                cc = JSON.parse(dd);
                for (var i = 0; i < cc.length; i++) {
                  if (cc[i].id == press) {
                    // console.warn(cc[i]);
                    var productData = cc[i];

                    var stri = JSON.stringify(cc[i]);
                    AsyncStorage.setItem('ProductData', stri);
                    var abc =await AsyncStorage.getItem('ProductData');
                    console.warn(stri);
                    console.warn(abc);
                  }
                }
              }}>

add async to function and add await

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM