Answer the question
In order to leave comments, you need to log in
How to make request Cancellation processing work?
I made a Pul component that makes a request to the server and processes it.
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function Pul() {
const [listImg, setLis] = useState([]);
const [resError, setResError] = useState("");
useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
(async () => {
try {
const Res = await fetch("https://kijo-3c490.firebaseio.com/.json", {
signal: signal
});
if (!Res.ok) {
throw new Error("Page Not Found 404");
}
const Product = await Res.json();
setLis(
Object.values(Product).filter(({ title }) => title.includes("New"))
);
} catch (error) {
setResError(error.message);
}
return () => {
abortController.abort();
};
})();
}, []);
console.log(listImg, resError);
return <div />;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Pul />, rootElement);
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import ProReqObj from "./ProcessingRequest";
Pul.jsx
function Pul() {
const [listImg, setLis] = useState([]);
const [resError, setResError] = useState("");
useEffect(() => {
(async () => {
const Res = await ProReqObj.Request1(
"https://kijo-3c490.firebaseio.com/.json"
);
if (typeof Res !== "string") {
setLis(Res);
} else {
setResError(Res);
}
})();
}, []);
console.log(listImg, resError);
return <div />;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Pul />, rootElement);
ProcessingRequest.jsx
class ProcessingRequest {
async Request0(URL) {
try {
const Res = await fetch(URL);
if (!Res.ok) {
return "Page Not Found 404";
}
const ProductArr0 = await Res.json();
return ProductArr0;
} catch (error) {
return error.message;
}
}
async Request1(URL1) {
try {
const ProductArr1 = await this.Request0(URL1);
if (typeof ProductArr1 === "string") return ProductArr1;
ProductArr1.filter(({ title }) => title.includes("New"));
return ProductArr1;
} catch (error) {
return error.message;
}
}
}
export default new ProcessingRequest();
Answer the question
In order to leave comments, you need to log in
One option is to add this to the class.
Request0() {
// this.abort()
// можно делать это тут, если запрос должен быть только один, а можно в useEffect
this.abortController = new AbortController()
// fetch
finally {
this.abortController = null
}
}
abort() {
if (this.abortController) {
this.abortController.abort();
this.abortController = null
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question