I’m making a call to a getTime function which returns the datetime, but for some reason the state I specify is not being updated, am I misunderstanding how this works? Do I need to await the result?
JavaScript
x
40
40
1
import * as React from 'react';
2
import {getTime} from '../utilities/time-helper'
3
4
export default class Landing extends React.Component {
5
constructor(props) {
6
super(props);
7
this.state = {
8
london: null,
9
paris: null
10
};
11
}
12
13
componentDidMount() {
14
this.setState({ london: getTime("Europe/London") });
15
this.setState({ paris: getTime("Europe/Paris") });
16
}
17
18
render() {
19
return (
20
<div>
21
<h1>London Time: {this.state.london}</h1>
22
<h1>Paris Time: {this.state.paris}</h1>
23
</div>
24
);
25
}
26
27
}
28
29
// time-helper.js
30
export function getTime(timezone) {
31
let url = 'http://worldtimeapi.org/api/timezone/' + timezone;
32
33
fetch(url)
34
.then(res => res.json())
35
.then((out) => {
36
return out.datetime
37
})
38
.catch(err => { throw err });
39
}
40
Advertisement
Answer
Yes, exactly, it’s a fetch, so you gotta wait for the result and set the state only then, so you could do smth like:
JavaScript
1
5
1
componentDidMount() {
2
getTime('Europe/London')
3
.then((response) => this.setState({ london: response });
4
}
5