Exercise: Form Validation and Context Management

Use what you've learned in this chapter to complete this coding exercise.

Problem statement

Our e-commerce website currently lacks login functionality for the users. Our objective is to facilitate user login and provide real-time error messages and personalized experience. The objective can be broken down into the following tasks:

  • Enable login: You’ll create a login mechanism using Next.js and the Context API. The user should be able to log in by providing valid username and password fields.

  • Manage state: Upon login, the username along with other data should be maintained across the application to provide a personalized feel to them.

  • Update cart name: The name of the cart should reflect the logged-in state of the user (more on this in the respective section).

  • Enable checkout: The cart page should be complemented by a checkout functionality that will only allow logged-in users to place orders.

Let’s explore each task in detail.

Enable login

You should ensure proper validation of the user’s input. Both the username and password input fields are required, and failing to provide inputs for either of them should result in an error. An error message should be displayed to the learners. An errorMessage state variable is initialized using the useState hook with an empty string as its initial value.

Note: You can utilize placeholder values like educative for both the username and password in an if-else statement for validation. If the entered username and password match educative, the user will be authorized; otherwise, you can use any name and password of your choice for testing.

We have already developed an interface for LoginForm.js, and your task is to incorporate form validations within this file.

Manage state

Next, you need to utilize the Context API to facilitate the sharing and management of state data among components. To accomplish this, employ the formData state variable initialized via the useState hook. This state encompasses an object comprising three attributes: usernamepassword, and isLoggedIn. The user must use the useUser function to set up the FormContext.

If you're unsure how to do this, click the “Show Hint” button.

Get hands-on with 1400+ tech skills courses.