Comments (11)
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.
Brilliant, thanks, this answers my questions for now
from react-hooks-async.
So, you are using start()
function. That sounds OK.
Can you share code snippet or preferably small codesandbox for reproduction?
from react-hooks-async.
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.
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.
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.
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.
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.
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.
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.
Thank you for the update @dai-shi
from react-hooks-async.
Related Issues (20)
- importing from src HOT 10
- infinite re-rendering when calling useAsyncTaskFetch hook HOT 2
- using asyncTask without useEffect HOT 9
- useFetch: Infinite re-rendering only when NODE_ENV=production HOT 12
- 3.1.0 breaks conditional running with useAsyncRun HOT 3
- useAsyncTaskFetch: pending is "true" from the start HOT 15
- Issue with tests and .start() since 3.2.0 HOT 2
- useAsyncTaskFetch doesn't provide access the response body if server returns error HOT 6
- what is the purpose of the started flag HOT 3
- Return a promise from task.start() HOT 5
- Support for react-native HOT 3
- Should we throw an error when fetch is aborted? HOT 4
- Typescript errors HOT 3
- How to handle FetchError? HOT 9
- Chaining async fetches HOT 2
- Error without statusText via HTTP/2 protocol HOT 7
- handling abort in useAsyncTask start().then HOT 2
- Unhandled promise rejection error HOT 6
- Project maintenance and future of data fetching HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-hooks-async.