Usually, when creating a form on React, a common approach is to use Formik (a React library to build forms) and yup (a JavaScript schema builder for value parsing and validation). If you follow this approach, after some time coding you’ll end up having a Formik component that uses a Yup schema in order to validate form values when needed, and that’s cool!

But what about handling multiple users with different permissions using the same Form component? For example: some users should see some inputs and some others shouldn’t, or maybe all users should see all inputs but some inputs are optional/required to some of them.

I want to show you a solution that I use: a builder schema function. Also, I’m going to compare some other approaches: using yup .when() mixed function, and multiple schemas, but first let’s set a scenario…

The scenario

Imagine you are developing a piece of software for a car rental company and they want a feature that allows customers to know if their cars are allowed to get into the car rental system, so car owners can get a commission.

And let’s say that after the user uploads their car info to the system, employees from the company can edit or upload more info about the car.

So, for now we have 2 user types: publicUser and companyMechanic, and these users have different permissions to edit the car info on the form with basic inputs: color, year, motor type and motor serial number.

Table with user permissions:

+--------------+--------------------+-----------------+
|  Car model   |                    |                 |
|  attributes  |     publicUser     | companyMechanic |
+--------------+--------------------+-----------------+
| color        | required           | required        |
| year         | required           | required        |
| motor type   | notRequired        | required        |
| motor serial |                    |                 |
| number       | notRequired        | required        |
+--------------+--------------------+-----------------+

There are some approaches to take

const carSchema = yup.object().shape({
  color: yup.string(),
  year: yup.number(),
  motorType: yup.string(),
  motorSerialNumber: yup.string(),
});

#formik #react #development #yup #programming

Manage Multiple User Permissions with Yup and Formik
6.00 GEEK