0

I'm new to react and I'm learning how to use useEffect. I encountered this warning in my react app. I tried out some solutions on SO but the warning still remains. Both fetchUser and fetchPosts trigger this warning. Can anyone enlighten me what is the problem and what does the warning mean?

App.js

  useEffect(() => {
    setLoading(true)
    const getUser = async () => {
      const userFromServer = await fetchUser()
      if (userFromServer) {
        setUser(userFromServer)
        setLoading(false)
      } else {
        console.log("error")
      }
    }
    getUser()
  }, [userId])

  useEffect(() => {
    const getPosts = async () => {
      const postsFromServer = await fetchPosts()
      setPosts(postsFromServer)
    }
    getPosts()
  }, [userId])

  useEffect(() => {
    const getUserList = async () => {
      const userListFromServer = await fetchUserList()
      setUserList(userListFromServer)
    }
    getUserList()
  }, [])

  // Fetch user 
  const fetchUser = async () => {
    const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
    const data = await res.json()

    return data
  }

  // Fetch posts
  const fetchPosts = async () => {
    const res = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
    const data = await res.json()

    return data
  }

  // Fetch list of users
  const fetchUserList = async () => {
    const res = await fetch('https://jsonplaceholder.typicode.com/users/')
    const data = await res.json()

    return data
  }
2
  • try move const fetchUser above useEffect before it being call Commented Feb 8, 2021 at 6:43
  • Thanks! I tried but the warning is still there. Commented Feb 8, 2021 at 6:48

1 Answer 1

0

If you are using any function or state which has been declared outside the useEffect then you need to pass it in the dependency array like this:


const someFunctionA = () => {
    ....
}

const someFunctionB = () => {
    ....
}
useEffect(() => {
    ....
}, [someFunctionA, someFunctionB])

You can read more about it here in case you want to know how it will be rendered: React useEffect - passing a function in the dependency array

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.