Creating API Hooks

We can also create Hooks for the various API calls. Putting these Hooks in a single file allows us to adjust the API calls easily later on. We are going to prefix our custom API Hooks with useAPI so it is easy to tell which functions are API Hooks.

Let's create custom Hooks for our API now using the following steps:

  1. Create a new src/hooks/api.js file.
  2. Import the useResource Hook from the react-request-hook library as follows:
import { useResource } from 'react-request-hook'
  1. First, we define a useAPILogin Hook to log in a user; we simply cut and paste the existing code from the src/user/Login.js file like so:
export function useAPILogin () {
return useResource((username, password) => ({
url: `/login/${encodeURI(username)}/${encodeURI(password)}`,
method: 'get'
}))
}
  1. Next, we define a useAPIRegister Hook; we simply cut and paste the existing code from the src/user/Register.js file as follows:
export function useAPIRegister () {
return useResource((username, password) => ({
url: '/users',
method: 'post',
data: { username, password }
}))
}
  1. Now we define a useAPICreatePost Hook, cutting and pasting the existing code from the src/post/CreatePost.js file, as follows:
export function useAPICreatePost () {
return useResource(({ title, content, author }) => ({
url: '/posts',
method: 'post',
data: { title, content, author }
}))
}
  1. Finally, we define a useAPIThemes Hook, cutting and pasting the existing code from the src/ChangeTheme.js file as follows:
export function useAPIThemes () {
return useResource(() => ({
url: '/themes',
method: 'get'
}))
}

As we can see, having all API-related functionality in one place makes it easier to adjust our API code later on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.182.179