简体   繁体   中英

Unable to get data using Fetch API in React

I've the following function that makes and api call and gets data.

export function getUserData(url){

  return fetch(url, { credentials : 'include'})
              .then((response) => { return response.json()})
              .then((data) =>{ return new User(data.uid, data.givenName, data.familyName)})
}

This is my User object.

class User{
  constructor(uid, givenName, familyName){

    this.uid = yguid;
    this.givenName = givenName;
    this.familyName = familyName;
  }
}
export default User;

Now in my react component I'm trying to instantiate the User object.

class Header extends React.Component {

    constructor(props) {
      super(props);
      this.state = { fullName: null, yguid: null };

    }
    componentWillMount(){
       user = getUserData(url);
       console.log(user);
       //set state with User data
    }

I've the following import statements in my React component.

import User from '../models/user';
import '../api/util';

Both my user and function getUserData are undefined. What am I doing wrong and how do I fix it. Thanks in advance.

your code user = getUserData(url) is setting user to a fetch promise. You need to also setup a resolver there. I would write it like

componentWillMount(){
 let user; 
 // getUserData actually returns a promise. resolve with a .then and set user to result
getUserData(url).then((result) => {
 user = result;

 console.log(user); // user should be defined here

 // not sure if user is a state object or not but if it is set it like this
 this.setState({user: user})
 })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM