简体   繁体   中英

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?

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

Solution put checkLocation inside useEffect

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM