GetItem with AsyncStorage in React Native is not working - android

I am new in react native and getting the bind value at index 1 is null when I am trying to get data from AsyncStorage in react-native below is my code.
Alert.alert(
'Info',
'React AsyncStorage',
[
{text: 'Get Data',onPress: () => this.getValue('name'),},
{text: 'Save Data', onPress: () => this.saveValue('name', 'abc'),}
],
{cancelable: false},
);
async saveValue(key:String, value:bool) {
AsyncStorage.setItem(key, value);
Alert.alert('Data', 'saving');
}
async getValue(key) {
// try {
// await AsyncStorage.getItem(Constant.SHOW_INTRO).then((value) =>
// console.log(`AsyncStorage GET for Constant.SHOW_INTRO: "${value}"`));
// } catch (error) {
// Alert.alert('Error', 'Error retrieving data');
// }
try {
const value = await AsyncStorage.getItem(key)
console.log(`AsyncStorage GET for "${key}": "${value}"`);
} catch (error) {
Alert.alert('Error', 'Error retrieving data');
}
}
Please help.

You can use this format:
setData = (value) => {
// if value is an Object use this: value = JSON.stringify(value)
// if value is a number use this: value = value.toString()
AsyncStorage.setItem('myKey', value, () => {
console.warn('Done!')
})
}
getData = () => {
AsyncStorage.getItem('myKey').then(storage => {
console.warn(storage)
}).catch(e => console.warn(e))
}
Then:
this.setData('sample text')
Edit:
AsyncStorage takes some time to fetch data so it returns a promise until the value is available. You have to call the then() function and get the value from there. Anything inside the then() function is called after the value is retrieved from storage.

Try doing it this way:
async getValue(key){
try {
const value = await AsyncStorage.getItem(key)
console.log(`AsyncStorage GET for "${key}": "${value}"`);
} catch (error) {
Alert.alert('Error', 'Error to retrieve data');
}
}

Related

React Native axios GET method to get all data from subpages and display them

Hello i'm new with axios and i wanna to display all my data from subpages to screen but I have some trouble because when I display them it shows me the data from the last subpage instead of all of them at the bottom I throw the code how I download the data through axios. How do I display them all ?
const [data, setData] = useState([]);
async function test() {
for (let id = 1; id < 3; id ++) {
axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`)
.then(({data}) => {
setData(data.commentData)
console.log(data.commentData)
})
.catch((error) => console.error(error))
}
}
useEffect(() => {
test()
}, []);
You are overwriting your data state in each loop, so the last loop iteration is the one that you see.
async function test() {
for (let id = 1; id < 3; id++) {
axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`)
.then(({ data }) => {
setData(data.commentData) // <-- overwrites previous state
console.log(data.commentData)
})
.catch((error) => console.error(error));
}
}
Use a functional state update to correctly update from the previous state.
async function test() {
setData([]);
for (let id = 1; id < 3; id++) {
axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`)
.then(({ data }) => {
setData(data => [...data, data.commentData]) // <-- append new data
console.log(data.commentData)
})
.catch((error) => console.error(error));
}
}
You could also map an array of Promises and use Promise.all to get a single array of resolved data values.
async function test() {
const requests = [1,2,3].map(id => axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`));
try {
const dataArr = await Promise.all(requests);
setData(dataArr.map(({ data }) => data.commentData));
} catch(error) {
console.error(error);
}
}

flutter stream shows error type '_TypeError' is not a subtype of type 'String'

I'm new to flutter, I need to read data from api and store in a list, but I get the error type '_TypeError' is not a subtype of type 'String', please help me
class HomeController extends ControllerMVC {
List<Slide> slides = <Slide>[];
HomeController() {
listenForSlides();
}
Future<void> listenForSlides() async {
final Stream<Slide> stream = await getSlides();
stream.listen((Slide _slide) {
setState(() => slides.add(_slide));
}, onError: (a) {
print(a);
}, onDone: () {});
}
Future<void> refreshHome() async {
setState(() {
slides = <Slide>[];
});
await listenForSlides();
}
}
the onError is an object not a string, if you want to print out the whole error stack object add a .toString():
onError: (a, stackTrace) {
print(a.toString());
}, onDone: () {});

AsyncStorage returns array to string react-native

I have an array that I stored on AsyncStorage as Json.stringfy. when I try to get the key it returns as a string. what I want is like this [0:'apple', 1:'ball', 2:'car']. following is the method I have tried
useEffect(() => {
AsyncStorage.getItem('#moduke').then(module => {
const a = JSON.parse(module);
console.log(a.length);
});
}, []);
the String is surrounded by " ". and use " . when try to parse the above string by JSON.parse(), still return the string:{"0:'apple', 1:'ball', 2:'car'}, and \" is replaced by ". But use the JSON.parse() again, it will return the object i solved as below method
useEffect(() => {
AsyncStorage.getItem('#moduke').then(module => {
const a = JSON.parse(module);
const b = JSON.parse(a);
console.log(b);
console.log(b.length);
});
}, []);

sqlite value not assigning to variable

I'm currently working with React native mobile application, on this process I use SQLite to store data locally within the phone the problem is I have assigned a variable getToken which need to be filled by the token I stored in SQLite DB. below is the method i tried and it always returns the default value.
function getTest() {
let getToken = 'ABC';
db.transaction(tx => {
tx.executeSql('SELECT * FROM Login', [], (tx, result) => {
getToken = result.rows.item(0).access_token;
});
});
return getToken;
}
The problem occurs because of transaction and executeSQL are async methods. Try using await or resolve a promise inside executeSQL callback. i solved this issue as follows
async function returnToken() {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql('SELECT * FROM Login', [], (tx, result) => {
let accessToken = result.rows.item(0).access_token;
resolve(accessToken);
});
});
});
}
async function (config){
let token = await returnToken();
console.log('token', token);
}

React native / Trouble with AsyncStorage get item

I am building an Android app and I am struggling using the AsyncStorage. I want to create a function that takes a key as input and give me back the item. My problem is that when I call this function, it returns { _40: 0, _65: 0, _55: null, _72: null } instead the value I am looking for.
Here is my code :
renderList() {
async function save() {
await AsyncStorage.setItem('Title', 'hello');
}
async function fetch(key) {
const value = await AsyncStorage.getItem(key);
console.log(value) ; // Return hello
return value
}
save() ;
fetch() ;
const reponse = fetch() ;
console.log(reponse) ; // Return { _40: 0, _65: 0, _55: null, _72: null }
return (
<Text style={styles.noteElementTitle}> Aa </Text>
)
}
Edit :
I tried this :
async function getBody() {
await save();
const response = await fetch('Title');
console.log(response);
this.setstate({ title : response}) ;
}
getBody() ;
But I still get an error : TypeError: undefined is not a function (evaluating 'this.setstate({ title: response })')
What you're seeing is the Promise object returned by a function marked async. You need to either use await when calling the function, or treat the value as a promise and use then and catch. For example:
await save();
const response = await fetch();
console.log(response);
or
save()
.then(() => fetch())
.then(response => console.log(response));
Also, keep in mind that you should not be using async functions inside a render function. In your code above, you'll want to put the result of your fetch() function into component state.

Categories

Resources