Code Monkey home page Code Monkey logo

Comments (11)

dai-shi avatar dai-shi commented on May 10, 2024 1

I see your problem. Thanks for sharing your example.

Now, useAsyncRun is provided for conditional execution, so you wouldn't need a new one.

The real problem is that useAsyncCombineSeq is not designed for chaining results.
In your case, access token can be used commonly for all requests, I would define as a separate task.

I've updated your example. https://codesandbox.io/s/amazing-shirley-pmc0b

Not sure if it solves your all use cases. Please feel free to share new examples if any.

from react-hooks-async.

ed-sparkes avatar ed-sparkes commented on May 10, 2024 1

Brilliant, thanks, this answers my questions for now

from react-hooks-async.

dai-shi avatar dai-shi commented on May 10, 2024

So, you are using start() function. That sounds OK.
Can you share code snippet or preferably small codesandbox for reproduction?

from react-hooks-async.

ed-sparkes avatar ed-sparkes commented on May 10, 2024

Will try and put together a codesandbox today. What i think i am after is away to not run a task when a dependency is unset. For example i have a combined task one that gets an access token and then a second one that calls api endpoint via axios. despite the fact i am using useAsyncCombineSeq the second one runs with no access token, is cancelled when the first one completes with access token and then runs again correctly. How do i avoid that inital run?

Is there anyway to put a condition on the task run if dependency not undefined?

from react-hooks-async.

dai-shi avatar dai-shi commented on May 10, 2024

Currently, deps is simply fed into useEffect, so you cannot stop a task by setting it to undefined.
With useAsyncCombineSeq, the second one is supposed to wait until the first one is resolved.
Look forward to your codesandbox.

from react-hooks-async.

ed-sparkes avatar ed-sparkes commented on May 10, 2024

Ok, so i worked out why the start doesnt really work. The start is run on click but after state change component re-renders and is then stopped again, so would require clicking the button to restart.

Reading about a bit including facebook/create-react-app#6917 (comment)
It seems that the conditionally fetch or run an async function the condition needs to be inside useEffect.

Something like this seems to work ....

Code sandbox here with an example of this https://codesandbox.io/embed/unruffled-robinson-8hnxw

import { useEffect } from "react";

export const useAsyncRunConditionally = (asyncTask, startCondition) => {
  console.log("start" + startCondition());
  const start = startCondition() ? asyncTask && asyncTask.start : undefined;
  const abort = asyncTask && asyncTask.abort;
  useEffect(() => {
    if (start) {
      start();
    }
  }, [start, startCondition]);
  useEffect(() => {
    const cleanup = () => {
      if (abort) {
        abort();
      }
    };
    return cleanup;
  }, [abort]);
};

export default useAsyncRunConditionally;

Can you see any issues with this, and if not would you entertain a PR to your library to support this?

from react-hooks-async.

digitaltopo avatar digitaltopo commented on May 10, 2024

I'm trying to do the same using the useAsyncTaskFetch helper. Adding the following code in my component causes the component to infinitely render, seems like the deps for this helper aren't wired up properly?

...
const deleteTask = useAsyncTaskFetch(
    'https://jsonplaceholder.typicode.com/posts/1',
    {
      method: 'DELETE',
    }
  );
...

Minimal Reproducible Example:
https://codesandbox.io/s/wonderful-cache-cjp0t?fontsize=14

What am I missing? Thanks for your help!

from react-hooks-async.

digitaltopo avatar digitaltopo commented on May 10, 2024

I rewrote the helper inside my own code to actually ask for deps instead of using the original arguments. Seems to work for me so far, something like:

const defaultInit = {};
const defaultReadBody = body => body.json();

const createFetchError = message => {
  const err = new Error(message);
  err.name = 'FetchError';
  return err;
};

const useAsyncTaskFetch = (
  {url: input, config = defaultInit, readBody = defaultReadBody},
  deps = []
) =>
  useAsyncTask(async abortController => {
    const response = await fetch(input, {
      signal: abortController.signal,
      ...config,
    });
    if (!response.ok) {
      throw createFetchError(response.statusText);
    }
    const body = await readBody(response);
    return body;
  }, deps);

export default useAsyncTaskFetch;

instead of https://github.com/dai-shi/react-hooks-async/blob/master/src/use-async-task-fetch.js

What I did makes sense I think, but would still like to understand if I'm missing something when I was trying to get it to work out of the box. If the original helper just has an oversight, happy to make a PR.

from react-hooks-async.

dai-shi avatar dai-shi commented on May 10, 2024

Please try defining the option outside of hooks, if they are independent.

const fetchOption = {
  method: 'DELETE',
};

const deleteTask = useAsyncTaskFetch(
  'https://jsonplaceholder.typicode.com/posts/1',
  fetchOption,
);

from react-hooks-async.

dai-shi avatar dai-shi commented on May 10, 2024

About the helper, I'm currently rewriting the entire API to avoid deps. This will be a breaking change.
This change is because of recent trend in React. The more idiomatic way seems to useMemo/useCallback at the caller end.

I will file a PR and ask a feedback from you.

from react-hooks-async.

digitaltopo avatar digitaltopo commented on May 10, 2024

Thank you for the update @dai-shi

from react-hooks-async.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.