-1

I have created a simple promise and when I call then on it, the promise is running twice.

import React from 'react'

function App() {

  let promise = new Promise(function (resolve, reject) {
    resolve("hello")
  })

  promise.then(function (res) {
    console.log(res)
  })
  return (
    <>
      Hello
    </>
  )
}

export default App

When I visit localhost:3000, and open debugger it shows "hello" printed twice. I am not able to understand what is going on. Please help

John
  • 23
  • 2
  • 1
    Because one time you `console.log(res)` which logs hello and one time you explicitly `console.log('hello')` which logs it a second time. – luk2302 Mar 14 '21 at 13:41
  • 1
    ?? There are two separate calls to `console.log("hello")` in the code you posted. – Pointy Mar 14 '21 at 13:42
  • @Pointy I put second console.log by mistake in the question. Even without that it is printing "hello" twice. Now I have edited the question, can you help me now? It will be very helpful. – John Mar 14 '21 at 13:51
  • [React.StrictMode](https://reactjs.org/docs/strict-mode.html) makes your code execute twice while in development mode to ensure you dont have state issues. Generally speaking, you should never call a Promise in a functional component without safe-guarding it with setState as it will be called/evaluated on every render – japrescott Mar 14 '21 at 15:52
  • Does this answer your question? [My React Component is rendering twice because of Strict Mode](https://stackoverflow.com/questions/61254372/my-react-component-is-rendering-twice-because-of-strict-mode) – buzatto Mar 15 '21 at 01:42
  • Thanks guys, now my problem is solved!!!!!! Thanks again. – John Mar 16 '21 at 02:04

1 Answers1

1

If you are using create-react-app, it's likely that your App is wrapped with StrictMode which causes an additional render of your App. Check your app's index.js.

fcFn
  • 322
  • 5
  • 13