Ukasha
Ukasha

Reputation: 2334

Async await and setTimeout are not working in ReactJS

You can see what I've done here.

import "babel-polyfill";
import React from "react";
import ReactDOM from "react-dom";

const asyncFunc = () => {
  return new Promise(resolve => {
    setTimeout(resolve("Gotcha!!!"), 10000);
  });
};

class App extends React.Component {
  state = {
    text: "Fetching..."
  };

  componentDidMount = async () => {
    const text = await asyncFunc();
    this.setState({ text });
  };

  render() {
    return <div className="App">{this.state.text}</div>;
  }
}

The app should show Fetching... first, then shows Gotcha!!! after 10 seconds. But, it's not working. What's my mistake?

Upvotes: 2

Views: 7076

Answers (3)

Farooq Hanif
Farooq Hanif

Reputation: 1899

import "babel-polyfill";
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const asyncFunc = () => {
  return new Promise(resolve => {
    setTimeout(() => resolve("Gotcha!!!"), 10000);
  });
};

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      text: "Fetching..."
    };
  }

  componentDidMount = async () => {
    const newText = await asyncFunc();
    this.setState({ text: newText });
  };

  render() {
    return <div className="App">{this.state.text}</div>;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370729

The problem is:

setTimeout(resolve("Gotcha!!!"), 10000);

The first argument to setTimeout should be a function. At the moment, you're calling resolve immediately as setTimeout tries to resolve its arguments (synchronously). Instead, pass it a function that then calls resolve:

setTimeout(() => resolve("Gotcha!!!"), 10000);

or

setTimeout(resolve, 10000, "Gotcha!!!");

Upvotes: 5

Abdullah
Abdullah

Reputation: 2111

You need to pass setTimeout a callback function, change it to this

setTimeout(() => resolve("Gotcha!!!"), 10000);

Upvotes: 1

Related Questions