Implementing registration

Next, we are going to implement registration, which is going to work in very similar way to creating posts.

Let's get started implementing registration:

  1. First, import the useEffect and useResource Hooks in src/user/Register.js:
import React, { useState, useContext, useEffect } from 'react'
import { useResource } from 'react-request-hook'
  1. Then, define a new useResource Hook, below the other Hooks, and before the handler functions. Unlike we did in the post creation, we now want to also store the resulting user object:
    const [ user, register ] = useResource((username, password) => ({
url: '/users',
method: 'post',
data: { username, password }
}))
  1. Next, define a new useEffect Hook below the useResource Hook, which will dispatch a REGISTER action when the request completes:
    useEffect(() => {
if (user && user.data) {
dispatch({ type: 'REGISTER', username: user.data.username })
}
}, [user])
Please note that, in this simple example, we do not expect, or handle the failure of registrations. In this case, we dispatch the action only after the successful creation of the user. However, when implementing login, we are going to handle error states from the request, in order to check whether the user was logged in successfully. It is best practice to always handle error states in real-world applications.
  1. Finally, we adjust the form submit handler in order to call the register function, instead of directly dispatching the action:
        <form onSubmit={e => { e.preventDefault(); register(username, password) }}>

Now, if we enter a Username and Password, and press Register, a new user will be inserted into our db.json file and, just like before, we will be logged in. We now move on to implementing login via Resource Hooks.

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

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