Using the useResource Hook

A more powerful way of dealing with requests, is using the axios and react-request-hook libraries. Using these libraries, we have access to features that can cancel a single request, or even clear all pending requests. Furthermore, using these libraries makes it easier to deal with errors and loading states.

We are now going to implement the useResource Hook in order to request themes from our server:

  1. In src/ChangeTheme.js, import the useResource Hook from the react-request-hook library:
import { useResource } from 'react-request-hook'
  1. Remove the previously defined State and Effect Hooks.
  1. Then, we define a useResource Hook within the ChangeTheme component. The Hook returns a value and a getter function. Calling the getter function will request the resource:
export default function ChangeTheme ({ theme, setTheme }) {
const [ themes, getThemes ] = useResource(() => ({
Here, we are using the shorthand syntax for () => { return { } }, which is () => ({ }). Using this shorthand syntax allows us to concisely write functions that only return an object.
  1. In this Hook we pass a function, which returns an object with information about the request:
        url: '/themes',
method: 'get'
}))
With axios, we only need to pass /themes as the url, because we already defined the baseURL, which contains /api/.
  1. The Resource Hook returns an object with a data value, an isLoading boolean, an error object, and a cancel function to cancel the pending request. Now, we pull out the data value and the isLoading boolean from the themes object:
    const { data, isLoading } = themes
  1. Then, we define a useEffect Hook to trigger the getThemes function. We only want it to trigger once, when the component mounts; therefore, we pass an empty array as the second argument:
    useEffect(getThemes, [])
  1. Additionally, we use the isLoading flag to display a loading message while waiting for the server to respond:
            {isLoading && ' Loading themes...'}
  1. Finally, we rename the themes value to the data value that is returned from the useResource Hook, and add a conditional check to ensure the data value is already available:
            {data && data.map(t =>

If we have a look at our app now, we can see that the Loading themes... message gets displayed for a very short time, and, then the themes from our database get displayed! We can now move on to requesting posts using the Resource Hook.

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

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