background

In a separate business scenario, apis are now the bridge between client and server.

Today we’ll talk about how to better manage apis with typescript and React hooks technology stacks.

Let’s look at some of the capabilities we need to use an API:

  1. When you declare an API, keep it simple, not too much boilerplate code, because we’re lazy.
  2. When we call the API, we have to tell us the input and output parameters we need, and we have to know which module it belongs to, because no one remembers the code they wrote before.
  3. When calling an API, keep it simple, tell us what to return, and don’t call it every dayThen, setState, setloadingSave data, waste time, also do not want to write more, because more lazy.
  4. Wait, there’s so much to be satisfied with, so let’s talk about those three today, because I’m lazy.

Now what typescript and React hooks can do for us.

As you’re smart enough to know, typescript type derivation can help us, and wrapping a custom hook seems to work, too. Let’s use some simple code to get around this.

API generating function

The following API generates functions to help us generate functions. It looks like the code can call createGetApi and generate a function based on the AXIOS configuration.


import { AxiosRequestConfig, Method } from 'axios'

type ApiConfig<Params = any, Data = any> = AxiosRequestConfig & {
	url: string method? : Method params? : Params data? : Params _response? : Data [x: string]: any } type Service<Params = any, Data = any> =(headParams: Params, otherSet? : object) = > ApiConfig<Params, Data>

constcreateGetApi = <Params = any, Data = any>( apiConfig: ApiConfig ): Service<Params, Data> => (headParams: Params, otherSet = {}) => { return { ... apiConfig, params: headParams, ... Const getUser = createGetApi< {id: number}, {userName: string, password: string} >({url: 'http', method: 'get' })Copy the code

When you mouse over it, it says something like this, so it looks like the API generated by createGetApi already knows what it wants.

We’ve got the first one we want, and half of the second one we want, and the second module doesn’t tell us, so let’s go ahead and enrich.

const nameSpace = {
    user: {
        getUser
    },
    analysis: {
        getUser
    },
}

export const useApi = () = > {
    return nameSpace
}

const TEST = () = > {
    const apis = useApi()
    return (
        <div>22</div>)}Copy the code

We use ts’s automatic derivation to tell us which modules to use and what APIS the modules have.

Now that we’ve done point one and point two, let’s look at point three.

requestor

As mentioned above, the third point is to wrap a custom hook, and then the hook receives the generated API as a parameter, so that the hook does not need to write a lot of code later.


const useFetch = <Params, Data>(apiConfig: ApiConfig<Params, Data>) => {
    const [loading, setLoading] = React.useState(false)

    const [data, setData] = React.useState<Data>()

    React.useEffect(() => {
        setLoading(true)
        axios(apiConfig)
            .then((response) => {
                setData(response.data as Data)
            })
            .finally(() => {
                setLoading(false)
            })
    }, [])

    return {
        loading,
        data
    }
}
Copy the code

So we’ve written a simple requestor based on point 3, and we’ve wrapped in some of the things that we don’t want to write, but error catches that we don’t want to write, and then we’ll use it and see what happens.

const TEST = () = > {
    const apis = useApi()
    const { loading, data } = useFetch(apis.user.getUser({ id: 22 }))
    
    if(! data) {return 'loading'
    }
    return (
        <div>{data.userName}</div>)}Copy the code

Click here to see, useFetch can recognize our API, and also tell us the API output parameter.

Change the API parameter to string.

It seems that the third point is also implemented, API and hook understanding.

conclusion

To summarize, the above example provides a simple and efficient API management solution.

Typescript’s derivation can help avoid errors and improve efficiency in coding.

React Hook brings more possibilities. UseFetch is an open source library, such as SWR.

The above scheme, the blogger has a more perfect scheme on Github, combined with rich business functions, you can pay attention to (had better help to a star) : github.com/fridaymarke…