Source

tools/hooks/useApi.ts

//
// useApi custom hook
//

import { useContext, useEffect, useState } from 'react'
import { ApiInterface } from '../../interfaces'
import { ApiContext } from '../../services/ApiManager'

/**
Custom Hook for retrieving a Spark API Interface

If you know the name and version of an API interface managed by
the API Manager, you can use this hook to get an instance of
that api interface.

```
import { useApi } from '@jcu/spark'

export default function MyComponent() {

    // get version 1 of the vampire-information api interface
    const vampireApi = useApi('vampires', '1')

    // now you can call vampireApi.getInfo('dracula') to find out about Dracula.
}
```
@category Hooks
*/

export function useApi<T extends ApiInterface>(apiName: string, apiVersion: string): T {

    const apiLibrary = useContext(ApiContext)
    const [api, setApi] = useState<T>(undefined)

    // re-fetch the API interface if the api library changes
    useEffect( () => {
        if (apiLibrary) {
            setApi(apiLibrary.getApiInterface(apiName, apiVersion))
        } else {
            setApi(undefined)
        }
    }, [apiLibrary, apiName, apiVersion])

    return api
}