Sniberb
Sniberb3y ago

snowberb – 10-37 Jun 15

Im trying to use AbortController but I cant find out how it really works. If I put it before the fetch, the fetch request gets ignored, it doesnt even start. And if I put it after the fetch, it will simply await the call without aborting. Any ideas?
const controller = new AbortController()

const handleInputChange = async (values) => {
controller.abort()
await fetch({values, signal})
}

return <Select onChange={handleInputChange} />
const controller = new AbortController()

const handleInputChange = async (values) => {
controller.abort()
await fetch({values, signal})
}

return <Select onChange={handleInputChange} />
9 Replies
lebouwski
lebouwski3y ago
calling abort will reject the promise what are you trying to do?
Sniberb
SniberbOP3y ago
every time I pick a value on the select I have to make a patch I just want to cancel the previous request if it didnt finish and the user selects a new value
lebouwski
lebouwski3y ago
const controllerRef = useRef()

const handleInputChange = async (values) => {
if (controllerRef.current) controllerRef.current.abort();
controllerRef.current = new AbortController();
await fetch({values, signal: controllerRef.current.signal })
controllerRef.current = undefined;
}

return <Select onChange={handleInputChange} />
const controllerRef = useRef()

const handleInputChange = async (values) => {
if (controllerRef.current) controllerRef.current.abort();
controllerRef.current = new AbortController();
await fetch({values, signal: controllerRef.current.signal })
controllerRef.current = undefined;
}

return <Select onChange={handleInputChange} />
Sniberb
SniberbOP3y ago
why ref?
lebouwski
lebouwski3y ago
to keep it for when you rerender
Sniberb
SniberbOP3y ago
it works thank you but I dk how I could have thinked of using ref
lebouwski
lebouwski3y ago
on the second call to handleInputChange you need to call the abort controller for the previous request, so it needs to be kept outside of the function, but created inside
Sniberb
SniberbOP3y ago
okay I get that
reactibot
reactibot3y ago
This thread hasn’t had any activity in 36 hours, so it’s now locked. Threads are closed automatically after 36 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1118851743103582238

Did you find this page helpful?