Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 31, 2023 02:13 am

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


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.





1
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.











1
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.















































1
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)
10
    })
11
})

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. 











1
  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.











1
 <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.































1
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. 



























1
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
        

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. 



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. 











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


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.



































































































1
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: { 
10
          ...data.getHeaders()
11
        },
12
        data : data
13
      };
14
    
15
    axios(config)
16
      .then(function (response) {
17
        // get access to the return data from the POST API endpoint

18
        const data = response.data
19
        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.



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.



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.



Original Link: https://code.tutsplus.com/tutorials/creating-a-blogging-app-using-reactjs-add-post--cms-28579

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code