简体   繁体   中英

react async hook how to do it

This is my react component..

const DashboardContext = React.createContext()

function DashboardStateProvider({ children }) {
  const wallet = useWallet()

  const Provider = DashboardContext.Provider

  if (wallet.account)
    return (
      <WithSubscription Provider={Provider} connectedAccount={wallet.account}>
        {children}
      </WithSubscription>
    )

  return (
    <Provider
      value={{
        
      }}
    >
      {children}
    </Provider>
  )
}

async function WithSubscription({ Provider, connectedAccount, children }) {
  // Juror ANT balances, 24h ANT movements and claimed subscription fees
  const data = await apiCALL(connectedAccount)

  // bla bla bla code here
}

function useDashboardState() {
  return useContext(DashboardContext)
}

export { DashboardStateProvider, useDashboardState }

The problem is that it shows an error when I use async on the withSubscription function. It's really mandatory, because in it, I am making an async call await apiCALL .

ERROR:

Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See react-invalid-hook-call for tips about how to debug and fix this problem.

Any ideas? I have to fix this and i am not a react developer, so I'd appreciate the direct answer what to change exactly.

UPDATE:

How do I use useDashboardState ?

import { useDashboardState } from '../components/Dashboard/DashboardStateProvider'

 const {
    data
  } = useDashboardState()

i'm not tested your code but i think problem here const DashboardContext = React.createContext() try to create this hook inside of function component

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM