-2

i'm new in react and i've got some issues with asynchronous fetch data :

i want to fetch github users

function fetchUser(username) {
  return fetch(`https://api.github.com/users/${username}`)
    .then(response => response.json())
    .then(data => data)
}

export function getUserData(username) {
  const object =  {
    profile: fetchUser(username),
  }
  console.log(object)
  return object
}

and this is my method in my component

componentDidMount() {
  getUserData(this.props.playerOne)
}

but this is what i got in my console

{profile: Promise}

i'm sure that i dont understand well this promise so could you help me to have not a Promise in my object but the data i'm fetching ? (if i log data in my fetch i got what i want)

  • Does this answer your question? [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) – jonrsharpe Nov 08 '20 at 11:23
  • not in my case, i think i dont understand how to resolve promise in my case with then() – Benoît Bargès Nov 08 '20 at 17:45
  • I'd recommend reading up on promises, then; they're pretty core to developing for the web. – jonrsharpe Nov 08 '20 at 17:46

1 Answers1

0

You can make this function async and wait for the promise resolution.

export async function getUserData(username) {
  const object =  {
    profile: await fetchUser(username),
  }
  console.log(object)
  return object
}

then in your componentDidMount

componentDidMount() {
  getUserData(this.props.playerOne)
    .then((profile) => { this.setState({ profile }) })
}
Sergey
  • 1,000
  • 8
  • 19
  • why do i have to do that and why then() cant resolve my promise ? – Benoît Bargès Nov 08 '20 at 17:46
  • Your promise will be resolved (or rejected) in the `getUserData ` function, the asynchronous function itself returns a promise with `object`. In `componentDidMount ` when you call `then` you have the opportunity to get that `object` and set it to React state. – Sergey Nov 08 '20 at 18:33