StochasticNerd StochasticNerd - 1 month ago 11
React JSX Question

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.

Answer

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