-2

My code is as follows:

//fetch tasks from server
      const fetchTasks=()=>{
    
        const fTask = async ()=>{
          const res = await fetch('http://localhost:5000/tasks')
          const data = await res.json()
    
          console.log("data", data)     
        }
    
        fTask()
    
      }
    
      fetchTasks()

I was expecting the data to be logged into the console only once, but for some reason, it is being logged twice. I tried debugger, but it too did not help.. thank you in advance..

Sarun Dahal
  • 377
  • 1
  • 5
  • 17
  • 1
    Do you have [`Strict Mode`](https://reactjs.org/docs/strict-mode.html) enabled? – pilchard Jul 21 '21 at 12:05
  • @pilchard Yes, it is enabled... However, no warnings as such in the console... – Sarun Dahal Jul 21 '21 at 12:08
  • 1
    Well that is your answer then, from the docs: 'Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. **This is done by intentionally double-invoking the following functions**...' – pilchard Jul 21 '21 at 12:09
  • @pilchard - disabling the strict mode helped, thanks a ton! – Sarun Dahal Jul 21 '21 at 12:13
  • But... they said why in their comment? – evolutionxbox Jul 21 '21 at 12:14
  • 4
    see: [Why my simple react component print console twice?](https://stackoverflow.com/questions/60825649/why-my-simple-react-component-print-console-twice) and [setTimeout callback called twice in React functional component?](https://stackoverflow.com/questions/65765897/settimeout-callback-called-twice-in-react-functional-component) – pilchard Jul 21 '21 at 12:14

1 Answers1

1
  1. Remove strict mode or turn it into <> </> fragments shortcut

do this instead

const fetchTasks= async ()=>{
      const res = await fetch('http://localhost:5000/tasks')
      const data = res.json()

      console.log("data", data)  
  }

  fetchTasks()
iamevansobeng
  • 435
  • 3
  • 7