Gatoyu
Gatoyu

Reputation: 692

How to call multiple hook functions depending on the result of the previous one

I made a custom hook to call my api with an async hook and a hook handling the page number.

A button "begin" make the first api call,

a button "next" should increment the page number counter and THEN call the fetch function of the async hook

When I do it naively, incrementing the counter then calling the fetch in a function onClick, of course the api call is made before the counter is incremented

import { useCounter, useAsyncFn } from 'react-use'

const useCallApi = _ => {
    const [pageNumber, {inc}] = useCounter(0)
    const [results, fetch] = useAsyncFn(apiCall({pageNumber: pageNumber}), [pageNumber])
    return {
        results,
        fetch,
        inc
    }
}

const App = _ => {
    const {results, fetch, inc} = useCallApi()

    return <>
        <Button onClick={fetch}>begin</Button>
        <Button
          onClick={_ => {
            inc()
            fetch()  //of course it is not working
          }}
        >next</Button>

        //... display results
    </>
}

Basically how do I do to call multiples hook functions and make sure that the associated value of the previous is updated before calling the next one ?

Upvotes: 1

Views: 1194

Answers (1)

cbdeveloper
cbdeveloper

Reputation: 31335

As per my comment on your question:

You could restructure your code to something like that.

Update some variable throuch the button with the inc() call, and move your fetch() call to a useEffect that runs based on that variable changing. That variable could be pageNumber, for example.

  useEffect(()=>{
    fetch()
  },[pageNumber]);

  return(
    <React.Fragment>
      <Button onClick={fetch}>begin</Button>
      <Button onClick={inc}>next</Button>

        //... display results

    </React.Fragment>
  );
}

Upvotes: 1

Related Questions