简体   繁体   中英

How can I cancel axios request by token?

I'm trying to cancel axios request by token in useEffect:

(But Axios freezes after cancelation and doesn't work for another requests) [it's strange]

// http-request.js

export const cancelelationSource = axios.CancelToken.source();

export const get = endpoint => {
  return axios.get(endpoint, {
    headers: { ...headers },
    timeout: 20000,
    cancelToken: cancelelationSource.token
  })
    .then(response => response.data)
    .catch(e => {
      console.log(e);
    });
}

then in component:

import { get, cancelelationSource } from './http-request';

const About = () => {
  useEffect(() => {
    get('http://localhost:3001/test2').then(data => console.log(data))
  }, []);
  return (
    <h1>About</h1>
  )
}

const App = () => {
  useEffect(() => {
    get('http://localhost:3001/test').then(data => console.log(data))

    return () => cancelelationSource.cancel();
  }, []);

  return (
    <div>
      <Link to="/about">About</Link>
    </div>
  )
}

render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="/about" element={<About />} />
    </Routes>
  </BrowserRouter>,
  document.getElementById('root')
);

request cancelation works well when I click on the About link. but second API fetch doesn't work in component <About />

I think axios cancels all requests... (Axios freezes for other requests) I want cancel previous requests but new request should be able to fetch data after change pages or redirect!

CancelToken and AbortController are one-shot things that cannot be reused after they are canceled. You must create a new token for the new query batch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM