acheese
acheese

Reputation: 59

React Fetch API Being Called Multiple Times on page load

I have a React application that is connected to a Flask backend. I have been struggling with authentication. I have a page that the user is redirected to after successful login. However, I am trying to get it so that if the user navigates to this path without logging in, they are redirected to the login page. This functionality seems to be working, but it is calling my backend API three times and I am not sure why.

function Overview() {
    const [userName, setUserName] = useState(""); 
    const history = useHistory();
    const location = useLocation();

    function checkLocation() {
        try {
            let comingFrom = location.state.comingFrom;
            const token = location.state.token;
            var login = token + ":unused"; 
            fetch("http://127.0.0.1:5000/api/resource", {
                    headers: {
                    Accept: "application/json",
                    "Access-Control-Allow-Origin": "*",
                    "Content-Type": "application/json",
                    Authorization: "Basic " + Buffer.from(login).toString("base64"),
                    },
                })
                .then((response) => response.json())
                .then((data) => {
                    setUserName(data["data"]);
                });
            
        } catch(error) {
            history.push({
                pathname: "/login"
              });
        }
    }

    checkLocation();


    return <h1>{userName}</h1>;
}

export default Overview;

Can someone please advise as to why it is being called three times?

Upvotes: 1

Views: 2315

Answers (1)

Besufkad Menji
Besufkad Menji

Reputation: 1588

you are calling checkLocation outside useEffect, since this function update state you get almost infinite loop.

Solution put checkLocation inside useEffect

useEffect(()=>{
checkLocation();
},[])

Upvotes: 1

Related Questions