Search code examples
reactjstypescriptsocket.iofetch-apiflask-socketio

Prevent fetch making unwanted requests


fetch is making multiple unwanted requests, I tried the below but it still makes 6 to 10 requests

const [allowParse, setAllowParse] = useState<boolean>(true);
socket.on("upload_finished", function (response) {
        if (allowParse === true) {
            console.log("parse start");
            fetch("start-parse", {method: "POST"});
            setAllowParse(false)
        }
    });

I also looked into this post but I can't use useEffect inside a conditional statement

How do I fix this?

If you are wondering how I receive upload_finished I am using flask socket-io

@app.route("/upload", methods=["POST", "GET"])
def upload_file():
    # Code handling file upload
    socketio.emit("upload_finished")

Solution

  • Well I found a workaround but it only works if you are using websockets

    Instead of using socket.on("event", () => {"do something"} we can use socket.once