function returning data but not showing
Clash Royale CLAN TAG#URR8PPP
function returning data but not showing
I have this component
const SummaryBar = props =>
const MainObject = props;
const localGetUserFromID = userID =>
getEmailFromId(userID).then(results =>
return results.data.Title; //Comment: This one returning friendly name
);
;
return (<span>Hello localGetUserFromID(MainObject.AuthorId)</span>)
but when I render it somehow the its only showing Hello and not the output I am getting from my localGetUserFromID function. Am I doing wrong? Note the AuthorId is being pass to an API and the MainObject came from the App Level,
FYI when I try to debug it using dev tools the function is retuning the text I am look for.
I have a question if I do that is the props already available inside the componentwillmount?
– Billy Peralta
32 secs ago
1 Answer
1
localGetUserFromID()
returns nothing, that is, undefined
, and that's why you see Hello
only.
localGetUserFromID()
undefined
Hello
And because localGetUserFromID()
makes an asynchronous call to get an email from user ID, it doesn't have to be in render()
method. Now this component is defined as a state-less component, but you can re-define it as a stateful component, call the getEmailFromId()
in componentDidMount()
life-cycle method, and use a return value as an internal state.
localGetUserFromID()
render()
getEmailFromId()
componentDidMount()
Then you can show a value of the internal state after Hello
.
Hello
class SummaryBar extends Component
// Skipping prop type definition.
constructor(props)
super(props)
this.state =
username: '',
componentDidMount()
const MainObject: AuthorId = this.props
getEmailFromId(AuthorId).then((results) =>
this.setState(
username: results.data.title,
)
)
render()
const username = this.state
return (
<span>
Hello username
</span>
)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You have an async function, meaning the data isn't available as return value of your promise call, but only available when it has completed. You should rather go for a stateful component, get the data in componentwillmount, and update the local state, and render that state (provided, you don't have another statemanagement in your app available)
– Icepickle
3 mins ago