0

I am trying to access the [[PromiseValue]] in my renderContent function to render the values to the user. I see the data in my console log, but somehow I am unable to access it.

class PersonalInfo extends Component {

    async fetchUser() {
        const res = await axios.get('/api/current_user')
        if(res)
            return res.data
    }


    renderContent() {
        if(this.fetchUser()) {
            const userdata = this.fetchUser()
            console.log(userdata)
            console.log(userdata.email)
        }
    }
}

render() {

        return <div>{this.renderContent()}</div>;
    }
RamSom
  • 29
  • 3
  • 2
    I think the problem you might be having is that the `renderContent` function is synchronous. So when you call `this.fetchUser` you actually get a promise, instead of the `userdata`. Try turning the `renderContent` function to an `async` function, or, call the `fetchUser` function during the component lifecycle, and update the Component `state`, to re-render the component. – guzmonne Aug 19 '19 at 13:44

1 Answers1

0

Try this:

async renderContent() {
    const userdata = await this.fetchUser()
    if(userdata)
    {
    console.log(userdata)
    console.log(userdata.email)
Bill Cheng
  • 926
  • 7
  • 9
  • I got this error when doing that: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead. I added the final render statement to my original question, do in need to change something there? – RamSom Aug 19 '19 at 14:57
  • @RamSom Like guzmonne said earlier in a comment, you're doing it wrong – never fetch data with Ajax in the render function. Trigger the fetchUser function in lifecycle methods (e.g. componentDidMount) and store the result in state. – JJJ Aug 19 '19 at 15:17
  • Thanks JJJ that helped, used the componentDidMount that did the trick – RamSom Aug 19 '19 at 15:57