Sean
Sean

Reputation: 647

How to console.log data retrieved from asynchronous api call?

I'm making an API call to a server and sending to a React component. I'm trying to work out if the data has been loaded successfully and how it looks once it is loaded.

However, when I console.log the data I obviously only receive a promise object. Does anyone know how to ensure the console.log only fires once the API call is complete? I've tried to use async and await although I've struggled to get it working.

import React from 'react'
import { Field, reduxForm } from 'redux-form'
import { connect } from 'react-redux'

// actions
import { getPlayers, deletePlayer } from '../actions'
// components
import RenderPlayer from './RenderPlayer'

class DeletePlayer extends React.Component {
  constructor (props) {
    super(props)
    this.players = null
    this.renderPlayerList = null
  }

  componentDidMount () {
    this.players = this.props.getPlayers()

    this.renderPlayerList = () => {
      //map over each player entry in database and send all details as props to rednderPlayer
      this.players = this.players.map((player) => { return <RenderPlayer {...player} /> })

      return this.players
    }

    console.log(this.players)

    return this.players
  }

  render () {
    return (
      <div>
        {this.players}
      </div>
    )
  }
}

export default connect(null, { getPlayers, deletePlayer })(DeletePlayer)

Upvotes: 0

Views: 2046

Answers (2)

Vl4dimyr
Vl4dimyr

Reputation: 916

Here is your code with async and await and a little clean up:

import React from 'react'
import { connect } from 'react-redux'

import { getPlayers, deletePlayer } from '../actions'

import RenderPlayer from './RenderPlayer'

class DeletePlayer extends React.Component {
  state = {
    players: [],
  }

  async componentDidMount () {
    const { getPlayers } = this.props

    try {
      const players = await getPlayers()

      console.log(players)

      this.setState({ players })
    }
    catch (error) {
      console.error(error)
    }
  }

  render () {
    const { players } = this.state

    return (
      <div>
        {players.map(player => <RenderPlayer {...player} />)}
      </div>
    )
  }
}

export default connect(null, { getPlayers, deletePlayer })(DeletePlayer)

Upvotes: 1

Nicolas Hevia
Nicolas Hevia

Reputation: 15827

If this.players returns a promise, you can use .then() to do something with its response.

this.players.then(res => console.log(res)).catch(err => console.log(err))

Upvotes: 3

Related Questions