Requests with Effect and State Hooks

First, we are going to request themes from our server, instead of hardcoding the list of themes.

Let's implement requesting themes using an Effect Hook and a State Hook:

  1. In the src/ChangeTheme.js file, adjust the React import statement in order to import the useEffect and useState Hooks:
import React, { useEffect, useState } from 'react'
  1. Remove the THEMES constant, which is all of the following code:
const THEMES = [
{ primaryColor: 'deepskyblue', secondaryColor: 'coral' },
{ primaryColor: 'orchid', secondaryColor: 'mediumseagreen' }
]
  1. In the ChangeTheme component, define a new useState Hook in order to store the themes:
export default function ChangeTheme ({ theme, setTheme }) {
const [ themes, setThemes ] = useState([])
  1. Then define a useEffect Hook, where we are going to make the request:
    useEffect(() => {
  1. In this Hook, we use fetch to request a resource; in this case, we request /api/themes:
        fetch('/api/themes')
  1. Fetch makes use of the Promise API; therefore, we can use .then() in order to work with the result. First, we have to parse the result as JSON:
            .then(result => result.json())
  1. Finally, we call setThemes with the themes array from our request:
            .then(themes => setThemes(themes))
We can also shorten the preceding function to .then(setThemes), as we are only passing down the themes argument from .then().
  1. For now, this Effect Hook should only trigger when the component mounts, so we pass an empty array as the second argument to useEffect. This ensures that the Effect Hook has no dependencies, and thus will only trigger when the component mounts:
    }, [])
  1. Now, all that is left to do is to replace the THEMES constant with our themes value from the Hook:
            {themes.map(t =>

As we can see, there are now three themes available, all loaded from our database through our server:

Three themes loaded from our server by using hooks!

Our themes are now loaded from the backend server and we can move on to requesting posts via Hooks.

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

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