DEV Community

Discussion on: 6 use cases of the useEffect ReactJS hook

Collapse
digitalbrainjs profile image
Dmitriy Mozgovoy

Or we can use a bit of magic :) (Live Demo)

import { useAsyncEffect } from "use-async-effect2";
import cpAxios from "cp-axios";

function TestComponent({url}) {
  const [cancel, done, result, err] = useAsyncEffect(
    function* () {
      return (yield cpAxios(url)).data;
    },
    { states: true }
  );

  return (
    <div>
      {done ? (err ? err.toString() : JSON.stringify(result)) : "loading..."}
      <button className="btn btn-warning" onClick={cancel} disabled={done}>
        Cancel async effect (abort request)
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
colocodes profile image
Damian Demasi Author

I definitely have to check Axios out!