Filip
Filip

Reputation: 945

Async function in componentDidMount doesn't work on second mount react

I've got a list of flags that when clicked on change the language of my app and the current language flag gets bigger.

For the current language, I'm using a different API that requires me to do an async process. It works when I run the app for the first time, but when I try to change it, the language changes, but the flag stays the same.

export default class FlagImage extends Component {
  state = {};
  componentDidMount() {
    this.getFlag();
    console.log("mounted"); //hundreds of logs
  }
  getFlag = async (name = this.props.name) => {
    const url = `https://restcountries.eu/rest/v2/alpha/${name}`;
    const res = await fetch(url);
    const json = await res.json();
    const flagURL = json.flag;
    this.setState({ flagURL });
  };

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

    return name ? (
      big ? (
        <img alt={`Flag ${name}`} src={this.state.flagURL} width="87px" height="58px" />
      ) : (
        <img alt={`Flag ${name}`} src={`https://www.countryflags.io/${name}/flat/32.png`} />
      )
    ) : (
      <div />
    );
  }
}

in my jsx:

        <div //this div works like a button
          className={styles["flag2"]}
          onClick={() => {
            this.setState({ open: !this.state.open });
          }}>
          <FlagImage name={this.getCountryCode()} big={true} />
        </div>

Upvotes: 0

Views: 181

Answers (1)

Babak Yaghoobi
Babak Yaghoobi

Reputation: 1985

try this:

export default class FlagImage extends Component {
  state = {};
  componentDidMount() {
    this.getFlag();
    console.log("mounted"); //hundreds of logs
  }

  componentDidUpdate(prevProps, prevState, snapshot){
     if (this.props.name !== prevProps.name || this.props.big !== prevProps.big) {
            this.getFlag();
     }
  }

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

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

    return name ? (
      big ? (
        <img alt={`Flag ${name}`} src={this.state.flagURL} width="87px" height="58px" />
      ) : (
        <img alt={`Flag ${name}`} src={`https://www.countryflags.io/${name}/flat/32.png`} />
      )
    ) : (
      <div />
    );
  }
}

Upvotes: 4

Related Questions