Skip to content
Advertisement

React set a state to the result of an API call

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?

import * as React from 'react';
import {getTime} from '../utilities/time-helper'

export default class Landing extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            london: null,
            paris: null
        };
      }

    componentDidMount() {
        this.setState({ london: getTime("Europe/London") });
        this.setState({ paris: getTime("Europe/Paris") });
    }

    render() {
        return (
                <div>
                    <h1>London Time: {this.state.london}</h1>
                    <h1>Paris Time: {this.state.paris}</h1>
                </div>
        );
    }
    
}

// time-helper.js
export function getTime(timezone) {
    let url = 'http://worldtimeapi.org/api/timezone/' + timezone;

    fetch(url)
    .then(res => res.json())
    .then((out) => {
        return out.datetime
    })
    .catch(err => { throw err });
}

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:

componentDidMount() {
  getTime('Europe/London')
    .then((response) => this.setState({ london: response });
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement