What I am trying to do is alert the company_id
that is in local storage.
import React, { Component } from 'react';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, Text, StyleSheet, View, } from 'react-native';
import * as pouchDB_helper from '../utils/pouchdb';
type Props = {};
export default class HomeScreen extends Component<Props> {
render() {
AsyncStorage.getItem('company_id', (err, result) => {
alert(result);
});
return (
<View style={styles.container}>
<Button title="Hi" onPress={this.doSomething} />
</View>
);
}
}
The following code works but I want to be able to do it from inside a helper function. If you see at the top, I have import * as pouchDB_helper from '../utils/pouchdb';
In there I have the following:
import React from 'react';
import { AsyncStorage } from 'react-native';
import PouchDB from 'pouchdb-react-native'
export async function pouchDB_config() {
return AsyncStorage.getItem('company_id', (err, result) => {
return result;
});
}
Instead of AsyncStorage.getItem()
code, if I do alert(pouchDB_helper.pouchDB_config())
I get an object with the following: {"_40":0,"_65":0,"_55"_null,"72":null}
I know I'm obviously not doing something right with the whole asynchronous nature of it all so if anyone has any guidance I would greatly appreciate it. I'm still not up to par with how to work with async functions in react native.
This is beacause when you call the function pouchDB_helper.pouchDB_config()
it returns a promise.
There are different ways to use this to your advantage.
In your util/pouchdb change the function as following:
export async function pouchDB_config() {
return await AsyncStorage.getItem('company_id');
}
Now you can call this function as follows:
pouchDB_config().then((company_id) => {
console.log(company_id);
});
Or you can call it anywhere else within an async function:
const otherAsyncFunction = async () => {
const company_id = await pouchDB_config();
console.log(company_id);
}
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.