Search code examples
reactjsauthenticationaxiosreact-hooksuse-effect

How can I get the updated value only from a useeffect without it first returning the initial value null?


I am creating an auth hook that checks whether user is authenticated from the server and returns the value.

export function useAuth() {
    const [isAuthenticated, setIsAuthenticated] = useState(null);

    useEffect(() => {
        let mounted = true;
        axios({
            method: 'GET',
            url: 'http://localhost:8000/api/still-authenticated/',
            headers: {
                'Content-type': 'application/json',
            },
            withCredentials: true,
        })
        .then((res) => {
            if (mounted) {
                setIsAuthenticated(res.data.isAuthenticated);
            }
        });

        return () => mounted = false;
    },[setIsAuthenticated])

    return isAuthenticated;
}

While testing the function I noticed that it first returns null and then updates the value with the axios fetch which is either true/false.

Now my question: Is there a way for me to only receive the updated value in react without the use of useeffect (I tried useLayoutEffect and it doesn't work either)?


Solution

  • I think the comments want you to do something like the following. I agree, use a loader while you are fetching data from the API.

    export function useAuth() {
        const [isAuthenticated, setIsAuthenticated] = useState(null);
    
        useEffect(() => {
            let mounted = true;
            axios({
                method: 'GET',
                url: 'http://localhost:8000/api/still-authenticated/',
                headers: {
                    'Content-type': 'application/json',
                },
                withCredentials: true,
            })
            .then((res) => {
                if (mounted) {
                    setIsAuthenticated(res.data.isAuthenticated);
                }
            });
    
            return () => mounted = false;
        },[isAuthenticated])
    
        return {isAuthenticated ? isAuthenticated : {/*INSERT LOADER HERE OR TEXT*/}};
    }