I’m building something that will get data from a database.
Right now I’m trying call to function getUserById() (that will call to DB via axios later), and at this time I want the line- this.getUserById(id).then((res) to retrieve the dummydata from inside getUserByID().
But I’m getting this error:
Uncaught (in promise) TypeError: this.getUserById(...).then is not a function
I might have added unnecessary code by trying to fix the problem aswell..
UserProfile.js
import React, { Component } from "react";
export default class UserProfile extends Component {
constructor(props) {
super(props);
this.getUserById = this.getUserById.bind(this);
this.state = this.initialState;
};
initialState = {
id: "",
firstName: "Initial",
lastName: "",
email: "",
phoneNumber: "",
address: "",
dateOfBirth: "",
country: "Initial",
city: "Initial"
};
getUserById(userId){
console.log("Inside Function - ID: " + userId);
const user = {
"firstName": "Test",
"lastName": "Testsson",
"email": "test@barkr.bork",
"phoneNumber": "123456",
"address": "Test 12b",
"dateOfBirth": "1990-01-01",
"country": "England",
"city": "London"
}
console.log(user);
return user;
}
async componentDidMount() {
const {location} = this.props;
const query = new URLSearchParams(location.search);
const id = query.get('id');
console.log("Inside UserProfile - ID: " + id);
this.getUserById(id).then((res) => {
this.setState({
firstName: res.data.firstName,
lastName: res.data.lastName,
email: res.data.email,
phoneNumber: res.data.phoneNumber,
address: res.data.address,
dateOfBirth: res.data.dateOfBirth,
country: res.data.country,
city: res.data.city
})
});
};
render() {
return (
<section id="userprofile-section">
<div className="userprofile-box">
<div id="userprofile-container1">
<div className="userprofile-card">
<div className="userprofile-cardframe">
<div id="userprofile-picture">
<h2 id="userprofile-avatartext">Avatar/Picture</h2>
</div>
<h2 className="userprofile-h1" >{this.state.firstName}</h2>
<h3 className="userprofile-h2">{this.state.city}</h3>
<h3 className="userprofile-h2">{this.state.country}</h3>
</div>
</div>
</div>
<div id="userprofile-container2">
</div>
</div>
</section>
);
}
}
Picture of error:
Error in Web Browser
Appreciate the help.
>Solution :
Your getUserById function does not return a promise, but a user object. As it seems you want to later use this function for an asynchronous operation, this problem should get solved when you do so (and return the promise).
To make it work with the temporary implementation, declare getUserById as an async function, and it should work.