Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to chain promise action? #166

Closed
wulucxy opened this issue Feb 2, 2020 · 2 comments
Closed

how to chain promise action? #166

wulucxy opened this issue Feb 2, 2020 · 2 comments

Comments

@wulucxy
Copy link

wulucxy commented Feb 2, 2020

I have two async requests,and one depend on the result of the other request:

const [{ data = {}, loading }] = useAxios({
    url: '/url1',
    params: { id },
  })

the next request need the value of data,so I need to write like this:

const [ ,findNext] = useAxios({
    url: '/url2',
  }, {
  manual: true
})

  useEffect(() => {
    if (data.code) {
      findNext({code: data.code})
    }
  }, [data])

this works,but it feels very ugly。I prefer the chained promise way,so do you have any advice, or
just write the normal useState way?

@simoneb

@simoneb
Copy link
Owner

simoneb commented Feb 2, 2020

There's an improvement you can do over this, but it feels like a little overkill to use hooks for it.

See the sample I put together here.

It's pretending to do something similar to what you're trying to achieve by first retrieving a list of todos and then requesting the details of the first of them, by its id property.

Basically, you create two manual requests and you use the Promise returned by invoking the refetch function of the first to extract the response and provide it as input to the second.

There's one drawback to consider here, which is a by-product of how the hook works. In your case you probably wouldn't want to cause the component to re-render after the first request completes and wait to get the response from the second instead. There is currently no way to achieve that with this library, because whenever any request triggered using the Hook gets a response, the component will re-render.
It may not be a big deal, but something to be aware of. For a scenario like this, I would consider not using the Hook in the first place.

@wulucxy
Copy link
Author

wulucxy commented Feb 3, 2020

@simoneb got it,thanks for your comment。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants