0

i have a realtime database fetch data function. but, when I pass the function through "useeffect", the data I receive is printed 2 times.

Here is fetch and set function:

  const SelectData = () => {
    get(child(dbref, 'GamePot Users/')).then((snapshot) => {
      if (snapshot.exists()) {
        snapshot.forEach((doc) => {
          let key = doc.key
          const childData = doc.val()
          const parsedChildData = JSON.parse(childData)
          const user = {
            id: key,
            value: parsedChildData,
          }
          setUsers((prevUsers) => [...prevUsers, user])
        })
      }
    })
  }

and function running useEffect:

  useEffect(() => {
     SelectData()
}, [])

and show this img on my console print

console print

thank you for you time.

zanthez
  • 45
  • 6
  • 1
    This is the effect of React 18 stress testing your application (in dev mode only) by running all useEffect twice. https://stackoverflow.com/questions/72238175/react-18-useeffect-is-getting-called-two-times-on-mount – Bao Huynh Lam Jul 07 '22 at 23:27
  • This might help too https://levelup.gitconnected.com/react-18-the-trickiness-of-useeffect-fadfa65fa4b4 – Brett East Jul 07 '22 at 23:28
  • @BaoHuynhLam raises a good point. You should probably change your `SelectData` to build an array and set that into state if that's what you expect to happen. That way your component can render as many times as you want without incorrect side-effects – Phil Jul 07 '22 at 23:33

0 Answers0