AsyncStorage.getItem is returning undefined - react-native

I'm setting a 'session' variable using AsyncStorage in my action file:
axios
...
// Session variable
AsyncStorage.setItem('userID', response.data.toString()).then((user) => {
this.setState({ user });
});
// Send to next page
NavigationService.navigate('Main');
Then, in my page, I tried to get the value:
...
render() {
AsyncStorage.getItem('userID')
.then((value) => {
const data = JSON.parse(value);
console.log('userID ', data.name);
});
...
It is returning 'userID undefined'. Why is it happening?
Thanks

The problem with the code you've written is that userId has the value 10 but when you call console.log you're treating it like an object with an attribute name. The correct code would look like:
...
render() {
AsyncStorage.getItem('userID')
.then((value) => {
const userId = JSON.parse(value);
console.log('userID ', userId); // This line changed
});
...

Related

Unable to set useState variable in async method and console log it

Im working with my friends on a app project and we find an issue many times when we tring to set a use state and the console log the variable, i've looking for a solution in the website and saw that the reason is that the usestate is an async awiat which means the variable that i set in the use state isn't immidatly set in it, so i tried many solution that i found in the websites but none of them work for me.
in the screenShot you can see that the json variable is in console log before and the set varaible doesn't show after the setActiveUser , any help?
Thanks!
If you want to do something upon setting state then your best bet is to use the useEffect hook from React and adding your state in the dependency array. This will then call the function in your useEffect every time the state changes. See below a rough example:
import { Text } from 'react-native';
const MyComponent = () => {
const [activeUser, setActiveUser] = useState(null);
useEffect(() => {
// This should log every time activeUser changes
console.log({ activeUser });
}, [activeUser]);
const fetchAuthentication = async user => {
var flag = false;
await fetch('/api/authUser/', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user),
})
.then(res => {
res.ok && (flag = true);
return res.json();
})
.then(json => {
if (flag) {
setActiveUser(json);
}
})
.catch(error => console.error(error));
return flag;
};
return <Text>Hi</Text>;
};
Full documentation: https://reactjs.org/docs/hooks-effect.html

Updating a state variable in React Native Expo

I dont really understand how setState and state variables update and work in React Native. Im trying to figure out what I did wrong in the code below, because I'm updating my tokenArray variable, but when I console log it in another function it is empty. Please help.
constructor() {
super()
this.state = {
tokenArr: []
}
}
componentDidMount() {
this.grabToken()
}
firebaseInformation = async () => {
var tokens = []
firebase.database().ref(`tokens/`).once('value', snapshot => {
const token = Object.values(snapshot.val());
token.map((item) => {
tokens.push(item.data)
})
return this.setState({
tokenArr: tokens
})
})
}
grabToken = async () => {
this.firebaseInformation()
console.log(this.state.tokenArr)
}
The fix was just to call the grabToken function in my render method instead (I was only calling it from my componentDidMount and didn't understand why it wasn't updating my state variable properly.
Return the array and set the state in componentDidMount() like this
componentDidMount() {
this.firebaseInformation()
.then((arr) => this.setState({ tokenArr: arr }))
.then(this.state.tokenArr);
}
firebaseInformation = async () => {
var tokens = []
firebase.database().ref(`tokens/`).once('value', snapshot => {
const token = Object.values(snapshot.val());
token.map((item) => {
tokens.push(item.data)
})
return tokenArr;
})
}

Get value from firestore collection in react native

I want to write a function that will get the value for the collection, as shown in the picture:
And here is my code, I really don't know what to do after the "then()":
const getLocation = () => {
firebase
.firestore()
.collection("users")
.doc(currentUser.uid)
.get()
.then((querySnapshot) => {});
};
Note that currentUser is redux, meaning that the query will execute only for the current user that is logged in
If you want to return the value of businessLocation only you can do this:
const getLocation = () => {
return firebase.firestore()
.collection("users")
.doc(currentUser.uid)
.get()
.then(function(doc) {
if (doc.exists) {
data = doc.data();
return data.businessDetails.businessLocation;
} else {
return "";
}
});
};
You can get more information on how to get data in firestore at the Official Documentation.
Note: This makes your function become an asynchronous function. Therefore you should call it as follows:
getLocation().then(result => {
//Do whatever you want with the result value
console.log(result);
})

How to access to the vue store in the asyncData function of nuxt

in a component i want to acces to the store with the asyncData function like so :
asyncData({ app, params }) {
var url = `https://myapi/news/${app.$store.state.market}/detail/${params.id}`;
return app.$axios.get(url).then(response => {
return { actu: response.data };
});
}
but i received "Cannot read property 'state' of undefined"
is there another to receive the state of the store here ?
You need to get store from context. Reference
asyncData({ app, params, store }) {
var url = `https://myapi/news/${store.state.market}/detail/${params.id}`;
return app.$axios.get(url).then(response => {
return { actu: response.data };
});
This worked for me
Store/index.js
...
state: {
loadedPages: []
}
...
Page
async asyncData(context) {
...
console.log(context.store.state.loadedPages)
...
}

how to get multiple fields from expo SecureStore

I am new to ES6 and react-native, trying to get multiple values from the SecureStore.
I think I am misunderstanding promises here ... global.userData is empty in the Promise.all(promises).then function. The relevant values do exist in the secure store
My code is:-
getUserData(fields) {
var promises = [];
var that = this;
global.userData = {};
function getField(field) {
return SecureStore.getItemAsync(field)
.then(res => {
console.log(field+"="+res); // this appears after the log below
global.userData[field] = res;
})
.catch(error => {
global.userData[field] = null;
});
}
fields.map(field => {
promises.push[getField(field)];
});
Promise.all(promises).then(function(v) {
console.log(global.userData); // this is empty
that.setState({ isReady: true }); // allow page to render
});
}
getUserData(["userId", "userName","etc"]);
My bad ... inadvertantly used
promises.push[getField(field)];
should have been:
promises.push(getField(field));
Suprised it wasn't detected as a syntax error ...