Bit of background, I have this API call that can be quite lengthy in its response (talking about over a minute in some instances, but 10-15 seconds for the most part). What I'd like to do is set a timeout on the client side while the backend continues to process the call. I'm using axios to handle http request and I know there is a timeout key that is default is 0 meaning that theres no timeout so the call will continue until either succeeds or fails. I tried to set it to 1 to see how this would handle a one millisecond timeout and the call is cancelled...which makes sense. My question now is, how can I implement a timeout on the client side without cancelling the HTTP request?
Some code to get your head around what I've tried.
import React from "react";
import axios from "axios"
function App() {
const fetchLongRequest = async () => {
try{
// All peachy over here if no timeout is implemented...
const myRequest = await axios({
url: "https://jsonplaceholder.typicode.com/todos/1",
headers: {
accept: "application/json",
"Content-Type": "application/json"
},
})
console.log("SUCCESS!", JSON.stringify(myRequest.data, null, 2))
}catch(error){
console.log("FAIL!", error.message)
}
}
return (
<button onClick={() => fetchLongRequest()}>Fetch</button>
);
}
export default App;
now this is my introduction of the timeout
import React from "react";
import axios from "axios";
function App() {
const fetchLongRequest = async () => {
// timeout works as expected but I'd like to let the call go to the backend and do its thing.
try {
const myRequest = await axios({
url: "https://jsonplaceholder.typicode.com/todos/1",
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
timeout: 1,
});
console.log("SUCCESS!", JSON.stringify(myRequest.data, null, 2));
} catch (error) {
console.log("FAIL!", error.message);
}
};
return <button onClick={() => fetchLongRequest()}>Fetch</button>;
}
export default App;
I know the request is a bit odd as it opens many questions such as error handling, how to know when this call is done, etc. I'd like to get some feedback in how I can achieve this task...please :)