0

I have a React component getting an item's info and returning JSX:

const detail = props => {

    const service = new Services()

    const detail = service.findItem(props.match.params.id)
        .then(item => {
            console.log(item) // logs correct details, including the title property
            return item
        })
        .catch(err => console.log(err))

    return (
        <h1>{detail.title}</h1> // !! prints nothing inside the <h1> tag
    )
}

As seen above, returning object logs correctly all properties, but when trying to access them through JSX, no info is shown.

There are no console errors.

Biomehanika
  • 1,530
  • 1
  • 17
  • 45
  • 1
    its because promise is async, and function will return the result before its completion . check this answer for better understanding [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Mayank Shukla Mar 24 '19 at 10:25
  • 1
    solution to your problem is use state and store the item in it, update the value it will reflect in ui once promise will be resolved. – Mayank Shukla Mar 24 '19 at 10:26
  • Thank you. So there's no way of getting this with a functional component? – Biomehanika Mar 24 '19 at 10:29
  • use the same function to make the api call and return the promise, call that method from main component and render the title as suggested above. – Mayank Shukla Mar 24 '19 at 10:30

1 Answers1

0

Its because the detail has not yet resolved, you can have React.Component and use

export class detail extends React.Component {

  state = { 
    item: {}
  }

  componentDidMount(){
    const service = new Services()
    const detail = service.findItem(props.match.params.id)
      .then(item => {
        this.setState({ item:item });
      })
      .catch(err => console.log(err))
}

  render() {
    return <h1>{this.state.item.title}</h1>
  }

}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
AlexZvl
  • 2,092
  • 4
  • 18
  • 32