0
votes

I am getting this warning and I was wondering what steps I need to take to remove the warning from my console. The issue being, I am using the fetchProfile() function elsewhere so I can't move it within the useEffect. any suggestions? My code is as follows:

  const fetchProfile = async () => {
    const token = await localStorage.FBIdToken
    await axios
      .get(`/user`, {
        headers: {
          Authorization: `${token}`
        }
      })
      .then(res => {
        setUser(res.data)
        setFormData({
          ...formData,
          github: res.data.user.github ? res.data.user.github : '',
          website: res.data.user.website ? res.data.user.website : '',
          linkedIn: res.data.user.linkedIn ? res.data.user.linkedIn : '',
          cohort: res.data.user.cohort,
          program: res.data.user.program
        })
      })
      .catch(err => console.log('error'))
  }

  useEffect(() => {
    fetchProfile()
  }, [])
2
also adding fetch profile into the dependency array does not remove the warning - Rob Terrell
Is your fetchProfile function defined within the component? - Jayce444
Yes my fetch profile has been defined within the component - Rob Terrell

2 Answers

0
votes

Wrapping the function in useCallback and adding it as a dependency should work, like so:

const fetchProfile = useCallback(async () => {
  // Do request as per normal
}, [])

useEffect(fetchProfile, [fetchProfile])

Another option is to move the fetchProfile function outside the component and pass in the setters to the call:

// This is defined outside your component
const fetchProfile = async ({ setUser, setFormData }) => {
  // Do request as per normal
}

useEffect(() => {
  fetchProfile({ setUser, setFormData })
}, [])
0
votes

You're getting the warning because you're using fetchProfile inside your hook, but not including it in the dependencies. If fetchProfile changes, your effect won't run.

To get rid of the warning, add fetchProfile to the dependencies (the second argument to useEffect()):

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