'The user aborted a request - ReactJS
I got an issue on my javascript program my project separate to 2 files:
- backend -> NodeJS (work fine I check the routes using POSTMAN and I got the Data.
- frontend -> I do get data from backend but I got an issue when I want to display all users (that located in DB).
on the frontend I got 2 files that got the issue: my hook -> http-hook.js:
import { useState, useCallback, useRef, useEffect } from "react";
export const useHttpClient = () => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState();
const actieveHttpRequests = useRef([]); //store data accross re render cycle (if the user change page before we finish the proccess with the DB)
//we use useRef and not useState because we dont wont to update the UI.
//when the component that use this hook re render
//useCallback make sure that there are no infinity loops when ever the component is rerender
const sendRequest = useCallback(
async (url, method = "GET", body = null, headers = {}) => {
setIsLoading(true);
const httpAbortCtrl = new AbortController(); //API Supported in modern browser
//current properties -> access to the data in useRef
actieveHttpRequests.current.push(httpAbortCtrl);
try {
const response = await fetch(url, {
method, //method: method
body,
headers,
signal: httpAbortCtrl.signal, //link the AbortController to this request
});
const responseData = await response.json();
actieveHttpRequests.current = actieveHttpRequests.current.filter(
(reqCtrl) => reqCtrl !== httpAbortCtrl
); //filter all the old request controller
if (!response.ok) {
//the response.ok will be true if the status code is 200
// not ok is mean we got 400 or 500
throw new Error(responseData.message); //trigger the catch block
}
setIsLoading(false);
console.log(responseData);
return responseData;
} catch (err) {
console.log("there is the error: " + err);
setError(err.message);
setIsLoading(false);
throw err;
}
},
[] //no specific dependecie so we add an empty array
);
const clearError = () => {
setError(null);
};
useEffect(() => {
//when we return a function in this first function than the return function is excecuted as a clean function
//before the next time use effect runs again or also when the component that uses useEffect unmounts
return () => {
actieveHttpRequests.current.forEach((abortCtrl) => abortCtrl.abort());
};
}, []);
return { isLoading, error, sendRequest, clearError }; //isLoading:isLoading , error:error
};
by using this hook I can send request to the backend and get my results.
You can Note that I put 2 line of code of console.log so on the image you can see that I do got the error, but than I got the results from the DataBase
on the other file UserList.js (here I wish to display my users, but the error in only on the useEffect function, I haven't try to display the data on the DataGrid, , I just try at first to get the DATA from the backend):
**
- UserList.js:
**
import React, { useState, useEffect } from "react";
import "./userList.css";
import { DataGrid } from "@mui/x-data-grid";
import { DeleteOutline } from "@material-ui/icons";
import { userRows } from "../../dummyData";
import { Link } from "react-router-dom";
import ErrorModal from "../../shared/components/UIElements/ErrorModal";
import LoadingSpinner from "../../shared/components/UIElements/LoadingSpinner";
import { useHttpClient } from "../../shared/hooks/http-hook";
const UserList = () => {
const [data, setData] = useState(userRows);
const { isLoading, error, sendRequest, clearError } = useHttpClient();
const [loadedUsers, setLoadedUsers] = useState();
const handleDelete = (id) => {
setData(data.filter((item) => item.id !== id));
};
useEffect(() => {
const fetchUsers = async () => {
try {
//with fetch, the default request type is GET request
const responseData = await sendRequest(
process.env.REACT_APP_BACKEND_URL + "/users"
);
setLoadedUsers(responseData.users); //users propeties is the given value from the backend (user-controllers.js on getUsers())
} catch (err) {}
};
fetchUsers();
}, [sendRequest]);
const columns = [
{ field: "id", headerName: "ID", width: 90 },
{
field: "user",
headerName: "Username",
width: 200,
renderCell: (params) => {
return (
<div className="userListUser">
<img className="userListImg" src={params.row.avatar} alt="" />
{params.row.username}
</div>
);
},
},
{ field: "email", headerName: "Email", width: 200 },
{ field: "status", headerName: "status", width: 120 },
{ field: "transaction", headerName: "Transaction Volume", width: 160 },
{
field: "action",
headerName: "Action",
width: 150,
renderCell: (params) => {
return (
<>
<Link to={"/users/" + params.row.id}>
<button className="userListEdit">Edit</button>
</Link>
<DeleteOutline
className="userListDelete"
onClick={() => handleDelete(params.row.id)}
/>
</>
);
},
},
];
return (
<React.Fragment>
<ErrorModal error={error} onClear={clearError} />
{isLoading && (
<div className="center">
<LoadingSpinner />
</div>
)}
{/* we need to render loadedUsers only if not empty*/}
{!isLoading && loadedUsers && (
<div className="userList">
<span className="Title">User List</span>
<div style={{ display: "flex", height: "80%" }}>
<div style={{ flexGrow: 1 }}>
<DataGrid
disableSelectionOnClick
rows={data}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection
/>
</div>
</div>
</div>
)}
</React.Fragment>
);
};
export default UserList;
to remind, on http-hoolk I put those 2 line of code: on the error:
console.log("there is the error: " + err);
on the results:
console.log(responseData);
Solution 1:[1]
I got no idea why but on my index.js I had this code:
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
All I had to do is remove the React.StrictMode and the error remove!
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<App />
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | idan noyshul |