0

So I have some logic I want to run on state change, but not on mount. The default state value is an empty object.(currentTarget is the state). So I figured an if statement would do the trick.

const fetchChat = async () => {
    const getChatData = await fetch('http://localhost:3001/getChat')
    const chatData = await getChatData.json()
    const checkForChat = chatData.some((chat) => {
      return chat.psuedoID.includes(userInfo._id) && chat.psuedoID.includes(currentTarget._id)
    })
    console.log(checkForChat)
    if (checkForChat === false) {
      createChat([userInfo._id, currentTarget._id])
    }
  }

  useEffect(() => {
    if (currentTarget !== {}) {
      console.log(currentTarget)
      fetchChat()
    }
  }, [currentTarget])

Despite the console log showing that the state hasn't changed and is still an empty object, the logic within the if statement is still running on mount.

  • I believe this "trick" should work: create a variable called firstRender set to true, and then in your useEffect a condition such as if firstRender is true, then set firstRender to false, else do whatever you need to do. – Emilien Dec 08 '22 at 19:49
  • Essentially the reason is that `{}` and `{}` may look the same, but they are different instances and therefore not "equal" as far as objects go. The linked duplicate provides a variety of options for testing if an object is empty. – David Dec 08 '22 at 19:49
  • @David Thanks a ton, testing for the length seem to have worked. Appreciate the help. – Romeo Richardson Dec 08 '22 at 20:01

0 Answers0