0

React showing missing dependancy, but everything seems ok. I dont want declare function inside useeffect, can you help with that?

Even if I declare all function codes inside usEffect, it tells then user token also missing dependancy. I dont understand what wants react here.. there is no examples in documentation.

const Profile = () => {

    const [user, dispatch] = useContext(UserContext)
    const [login, setLogin] = useState('waiting')
    let [selected, setSelected] = useState('video')
    let [section, setSection] = useState()
    const [userdata,setUserData] = useState()

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

    let checkCurrentUser = async () => {
        console.log(user.token)
        let result = await requestCurrentUser(user.token)
        if (result.status) {
            await dispatch({
                type: "USER",
                payload: result.data
            })
            setUserData(result.data)
            setLogin('success')
        } else {
            setLogin('failed')
        }
    }

    if (login === 'waiting') {
        return (
            <PianoPlay width={300} classAdd="loading" />
        )
    }
    else if (login === 'failed') {
        return (
            <Redirect push to="/" />

        )
    }

    else if (!userdata.hasOwnProperty('id')) {
        return (
           <Redirect push to="/home" />
        )
    }
zero298
  • 25,467
  • 10
  • 75
  • 100

1 Answers1

0

You can solve this in two ways.

1 - useEffect(checkCurrentUser, [])

2-

const checkCurrentUser = useCallback(() => {
      ...
    }, [])
    useEffect(() => {
      checkCurrentUser()
    }, [checkCurrentUser])
  • Thanks for reply, checked 1 still problems with async, second I think is too complicated. I cant understand why we cant use function inside useEffect and there is no official documentation for that – Orhan Taghizadeh Jan 22 '21 at 17:57