2

Creating a Blogging App Using React, Part 2: User Sign-Up

 1 year ago
source link: https://code.tutsplus.com/tutorials/creating-a-blogging-app-using-reactjs-add-post--cms-28579
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In this series, we aim to create a blog using functional React components.

In the first part of this tutorial, we saw how to implement the sign-in functionality. Now, let's move to the sign up functionality. 

Getting Started

Let's get started by cloning the GitHub repo from the first part of the tutorial.

git clone https://github.com/tutsplus/create-a-blogging-app-using-react

Once the directory has been cloned, navigate to the project directory and install the required dependencies.

cd my-blog
2
npm install

And, you should be able to see the application at https://localhost:3000

And, the express server should be running at http://localhost:5000

The Server

Previously, we saw how to GET sign in data from our PSQL database. However, you have the freedom to choose any database for building the employee table. MongoDB is another popular choice.

To sign up, we need to post data into the database. To achieve this, we have to introduce the following piece of code in app.js. The following snippet will insert a new user into the users table. If something goes wrong during the insertion, an error will be thrown.

app.post('/api/posts/userprofiletodb', (req, res, next) => {
2
    const values = [req.email, 
3
                    req.pwd]
4
    pool.query(`INSERT INTO users(username, email, pwd, date_created)

5
                VALUES($1, $1, $2, NOW())

6
                ON CONFLICT DO NOTHING`, values,
7
            (q_err, q_res) => {
8
              if(q_err) return next(q_err);
9
              res.json(q_res.rows)
    })
})

The Client

As we are using the Functional React Component, useState and useReact will help us manage the state of the component.

Capturing Values

For each field in the sign up form, we will have a state variable to listen to its changes. By default, these values are empty. 

  const [email, setEmail] = useState('')
2
  const [password, setPassword] = useState('')

The email, and password defined using useState has to be linked to the form elements. This can be achieved easily using the value property.

 <input type="text" id="inputName" value={email} className="form-control" placeholder="Name" required autoFocus />
2

And, it is important to change the value of the email and password state on user input. This can be achieved using the onChange property. When a user enters a value in the email field, the handleEmailChange function will be called and set the value of the email state, using the setEmail method. 

This is the most interesting part of useState in React functional components. State is initialized as a pair: a variable, and a function which can be called to set the value of the variable. In our case, email is the variable, and setEmail is the function to assign a value to email.

const handleEmailChange = (event) => {
2
    setEmail(event.target.value)
3
}
4
5
6
<input type="text" id="inputEmail" value={email} onChange={handleEmailChange} className="form-control" placeholder="Email" required autoFocus />
7

The above logic can be applied to the password field. 

const handlePasswordChange = (event) => {
2
    setPassword(event.target.value)
3
}
4
5
<input type="password" id="inputPassword" value={password} onChange={handlePasswordChange} className="form-control" placeholder="Password" required />
6
Advertisement

Validating Changes

One of the biggest perks in using native elements is validation.

When the type of the input field is email, the native element validates if the data entered is valid or not. For example, if the email entered is invalid, a native popup will appear when the user clicks on the submit button. 

Screenshot_2023_01_21_at_8_57_04_AM.png

Screenshot_2023_01_21_at_8_57_04_AM.png

Screenshot_2023_01_21_at_8_57_04_AM.png

Likewise, we can fix the minimum number of characters to be entered in a field using the minlength property of the input element. This check would throw an error if the user has entered fewer characters. One of the places where we can use this check is on the password. 

<input type="password" minlength="8" id="inputPassword" value={password} onChange={handlePasswordChange} className="form-control" placeholder="Password" required />
2

Screenshot_2023_01_21_at_9_29_00_AM.png

Screenshot_2023_01_21_at_9_29_00_AM.png

Screenshot_2023_01_21_at_9_29_00_AM.png

Sign Up

If the user has entered right data, the sign up post call can be made.

Define a signup method called handleSubmit. Inside the handleSubmit method, make a post method call to the signup API endpoint.  Here, I'm using the Axios library for fetching.

const handleSubmit = () => {
2
      var data = new FormData();
3
      data.append('email', email);
4
      data.append('pwd', password);
5
6
      var config = {
7
        method: 'get',
8
        url: `http://localhost:5000/api/get/userprofilefromdb?email=${email}`,
9
        headers: { 
          ...data.getHeaders()
        },
        data : data
      };
    axios(config)
      .then(function (response) {
        // get access to the return data from the POST API endpoint

        const data = response.data
        navigate("/landing")
20
      })
21
      .catch(function (error) {
22
        setError(error.message)
23
      });
24
    }

Many a times, developers wonder if they should choose Axios or fetch for their Single Page Application. Axios is often the common pick. Here are few reasons why.

  • Axios is much more secure than the Fetch API. Axios comes with cross-site forgery protection.
  • fetch is not supported in older IE browsers. This means, a polyfill has to be written if your application is likely to be opened in older browsers.
  • Requests made using fetch cannot be aborted. 
  • fetch does not allow request timeouts. The timeout logic has to be implemented by the client-side application.

The Sign Up Page in Action

With all these elements put together, you will see the Sign Up page as below.

Screenshot_2023_01_21_at_9_23_42_AM.png

Screenshot_2023_01_21_at_9_23_42_AM.png

Screenshot_2023_01_21_at_9_23_42_AM.png

If the API endpoint returns a response, the user can be redirected to the /landing blog page. And, if the API endpoint throws an error, the error will be displayed on the screen.

Screenshot_2023_01_21_at_9_27_01_AM.png

Screenshot_2023_01_21_at_9_27_01_AM.png

Screenshot_2023_01_21_at_9_27_01_AM.png

Advertisement

A Working Demo

Here is a working demo in StackBlitz for your reference.

Wrapping it Up

In this part of the tutorial, you saw how to implement the user sign-up process. We saw different types of validations, different ways of calling an endpoint, and a simple server side change.

In the next part of the tutorial, you'll implement the add post and display post page functionality.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK