import axios from "axios";
import { useState } from "react";
import Router from 'next/router'



export default function useUser(props) {

    useEffect(() => {
        const [user, setUser] = useState(null)
        axios({
            url: "http://localhost:8000/users/username/",
            method: "GET",
            withCredentials: true
        }).then((res) => {
            setUser(res.data.username)
        }).catch((err) => {
            console.log(err)
        })
        // if no redirect needed, just return (example: already on /dashboard)
        // if user data not yet there (fetch in progress, logged in or not) then don't do anything yet
        if (!props.redirectTo || !user) return

        if (props.redirectTo && !user) {
            Router.push(redirectTo)
        }
    }, [user])

    return user
}