Search code examples
reactjspromisefetch

React and promise issues with fetch method


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)


Solution

  • 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 }) })
    }