alexlafroscia / use-task

A React hook for running and cancelling asynchronous tasks
https://use-task.now.sh
24 stars 1 forks source link

Cancel an "inner" task performance when an "outer" is cancelled #4

Closed alexlafroscia closed 5 years ago

alexlafroscia commented 5 years ago

Much like ember-concurrency, I want to somehow determine when a task is performed within another task, so that cancelling the outer also cancels the inner. This is what I hope to achieve:

function MakeRequest() {
  const [makeRequest] = useTask(function*() {
    yield fetch(/* ... */);
  });

  return <HandleClick onClick={makeRequest} />;
}

function HandleClick({ onClick }) {
  const [handleClick] = useTask(function*() {
    yield onClick();
  });

  const lastInstance = useRef();

  return (
    <>
      <button
        onClick={() => {
          lastInstance.current = handleClick();
        }}
      >
        Run Action
      </button>
      <button
        onClick={() => {
          if (lastInstance.current && lastInstance.current.isRunning) {
            lastInstance.cancel();
          }
        }}
      >
        Cancel Action
      </button>
    </>
  );
}

So that, when the HandleClick component cancels the task, the inner task that is making the fetch will also be cancelled