Reputation: 35
Hi i'm trying to fetch a user data from jsonplaceholder and update my state with that data. I had no problem fetching the data and logging it to the console. But when i try to setState, i still get an empty object. I appreciate any help. Thanks.
This is my code:
class ProfilePage extends React.Component {
state = {
profileDetails: {},
};
componentDidMount() {
this.fetchDetails();
}
fetchDetails = async () => {
const baseUrl = "https://jsonplaceholder.typicode.com";
const pathname = this.props.history.location.pathname;
const response = await fetch(`${baseUrl}${pathname}`);
const data = await response.json();
console.log(data); // I can see the data i want here in the console.
this.setState = { profileDetails: data };
console.log(this.state.profileDetails); // I get an empty object here.
};
render() {
return <h1>Name: {this.state.profileDetails.name}</h1>;
}
}
export default ProfilePage;
Thanks everyone for taking the time to answer. Apparently i used setState wrong and missed the fact that it's asynchronous.
Upvotes: 2
Views: 95
Reputation: 5521
From docs of setState
React does not guarantee that the state changes are applied immediately.
If you want to use up-to-date data, use callback argument (and use it as function, instead of assignment, because it is a method, not a property)
this.setState({ profileDetails: data }, () => {
console.log(this.state.profileDetails)
})
Upvotes: 6
Reputation: 961
Change this
this.setState = { profileDetails: data };
console.log(this.state.profileDetails);
into this
this.setState({ profileDetails: data });
Put console.log(this.state.profileDetails);
inside render for you to see your new state.
setState is a function that recieves data as parameters. but you use it like setState is a json object
Upvotes: 3
Reputation: 793
The right way to set state is this,
this.setState({ profileDetails: data })
You have to set state by this way only.
Upvotes: 2
Reputation: 149
setState - is a method. Please change code like this - this.setState({ profileDetails: data });
Upvotes: 2
Reputation: 1220
Give a condition for check the data is available or not:-
if(data)
this.setState = ({ profileDetails: data });
Upvotes: 0