Home > Enterprise >  How to get value from object property in React or Javascript
How to get value from object property in React or Javascript

Time:10-31

Why do I have to wrap await with () in order to get the output I need. I am hoping to get only the uid from the object

The data that is return from the function that I am importing is exactly how you see it

{uid : 'abcdefg', email:'[email protected]'}
import {ActiveUser} from './teamMembers.service';

export const retrieveList = async date => {
console.log('active user information here', (await ActiveUser()).uid); 
// outputs: Works as expected
// active user information here abcdefg

console.log('active user information here', await ActiveUser().uid); 
// outputs: 
//Undefined

console.log('active user information here', typeof (await ActiveUser()));
// outputs: 
// object
}

CodePudding user response:

The await operator is used to wait for a Promise (The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value) and it can only be used inside an async function.

You need to await you're async task (ActiveUser) once and after that you can just reference it's data (which is the resolved state of that async code happening there)

import {ActiveUser} from './teamMembers.service';

export const retrieveList = async date => {
   const data = await ActiveUser();
   const uid = data.uid;
   const name = data.name;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I suggest you read more The event loop and the concurrency model and it's secret behind the JavaScript's asynchronous programming.

More about async - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

More about event loop - https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

  • Related