0

I need to use an async function in my render() function in React. How could I do that? What I am getting now is just a Promise, obviously.

import React, { Component } from "react";

export default class FlagImage extends Component {
  getSrc = async name => {
    const url = `https://restcountries.eu/rest/v2/alpha/${name}`;
    const res = await fetch(url);
    const json = res.json();
    const flagURL = json.flag;
    return flagURL;
  };

  render() {
    const { name } = this.props;

    return name ? <img alt={`Flag ${name}`} src={this.getSrc(name)} /> : <div />;
  }
}

3 Answers 3

3

Your async function returns promise which can't work with src. You can store that value in state and use it.

import React, { Component } from "react";

export default class FlagImage extends Component {
  state = { imageSrc: "" }
  getSrc = async name => {
    const url = `https://restcountries.eu/rest/v2/alpha/${name}`;
    const res = await fetch(url);
    const json = res.json();
    const flagURL = json.flag;
    setState({imageSrc: flagURL})
  };

  componentDidMount() {
    this.getSrc();
  }

  render() {
    const { name } = this.props;

    return name ? <img alt={`Flag ${name}`} src={this.state.imageSrc} /> : <div />;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

you beat me to it!
1

You should do that kind of stuff in componentDidMount lifecycle method.

Can you try this.

import React, { Component } from "react";

export default class FlagImage extends Component {

  state = {
   url = '' 
  };
  
  componentDidMount () {
    let url = this.getSrc();
    
    this.setState({
      url
    });
  }

  getSrc = async name => {
    const url = `https://restcountries.eu/rest/v2/alpha/${name}`;
    const res = await fetch(url);
    const json = res.json();
    const flagURL = json.flag;
    return flagURL;
  };

  render() {
    const { name } = this.props;

    return name ? <img alt={`Flag ${name}`} src={this.state.url} /> : <div />;
  }
}

Comments

1

Call that function inside lifecycle method

componentDidMount(){
  this.getSrc(); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.