Reputation: 1691
I have component named 'App':
export default class App extends Component {
state = {
data: {
id: null,
created: null
},
clicked: false,
loading: true
};
render() {
const data = this.state.data.id === null ? null : <Data data={this.state.data}/>;
const title = this.state.clicked ? <TitleDone/> : <Title/>;
return (
<div>
{title}
<div className="main">
<button
className=" btn btn-outline-secondary"
onClick={() => {
this.setState(() => {
return {
data: api.getResource(),
clicked: true
};
});
}}>
Нажать
</button>
</div>
<div className="main">
{data}
</div>
</div>
);
}
}
When I press Button, component 'Api' sending request to backend and I reseive JSON with 2 fields: id, created.
Request:
getResource = async () => {
const res = await fetch(`${this._apiPath}${this._logUrl}`);
if (!res.ok) {
throw new Error(`Could not fetch ${this._logUrl}` +
`, received ${res.status}`)
}
return await res.json();
};
res.json():
Network.Response:
{"id":87,"created":"2019-04-18 17:26:28.948"}
As we see, JSON wrapped into Promise. It comming to 'App' as undefined, and after response this.state.data looking like:
data: {
id: undefined,
created: undefined
}
Please give me advice, how to obtain data correctly and send it to component 'App'. Or, may be, there is another way to do it?
Upvotes: 1
Views: 100
Reputation: 1507
And you do not need await for return res.json()
getResource = async () => {
const res = await fetch(`${this._apiPath}${this._logUrl}`);
if (!res.ok) {
throw new Error(`Could not fetch ${this._logUrl}` +
`, received ${res.status}`)
}
return res.json();
};
Upvotes: 0
Reputation: 112777
getResource
is asynchronous, so you need to wait for the promise that is returned to be resolved before you put it in your component state.
<button
className=" btn btn-outline-secondary"
onClick={async () => {
this.setState({
data: await api.getResource(),
clicked: true
});
}}
>
Нажать
</button>
Upvotes: 3